//經過主鍵查詢第一條記錄 db.First(&user) //// SELECT * FROM users ORDER BY id LIMIT 1; // 隨機取一條記錄 db.Take(&user) //// SELECT * FROM users LIMIT 1; // 經過主鍵查詢最後一條記錄 db.Last(&user) //// SELECT * FROM users ORDER BY id DESC LIMIT 1; // 拿到全部的記錄 db.Find(&users) //// SELECT * FROM users; // 查詢指定的某條記錄(只可在主鍵爲整數型時使用) db.First(&user, 10) //// SELECT * FROM users WHERE id = 10;
// 獲取第一條匹配的記錄 db.Where("name = ?", "jinzhu").First(&user) //// SELECT * FROM users WHERE name = 'jinzhu' limit 1; // 獲取所有匹配的記錄 db.Where("name = ?", "jinzhu").Find(&users) //// SELECT * FROM users WHERE name = 'jinzhu'; // <> db.Where("name <> ?", "jinzhu").Find(&users) // IN db.Where("name IN (?)", []string{"jinzhu", "jinzhu 2"}).Find(&users) // LIKE db.Where("name LIKE ?", "%jin%").Find(&users) // AND db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users) // 時間 db.Where("updated_at > ?", lastWeek).Find(&users) // BETWEEN db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
// Struct db.Where(&User{Name: "jinzhu", Age: 20}).First(&user) //// SELECT * FROM users WHERE name = "jinzhu" AND age = 20 LIMIT 1; // Map db.Where(map[string]interface{}{"name": "jinzhu", "age": 20}).Find(&users) //// SELECT * FROM users WHERE name = "jinzhu" AND age = 20; // 主鍵的切片 db.Where([]int64{20, 21, 22}).Find(&users) //// SELECT * FROM users WHERE id IN (20, 21, 22);
db.Where(&User{Name: "jinzhu", Age: 0}).Find(&users) //// SELECT * FROM users WHERE name = "jinzhu";
你可使用指針或實現 Scanner/Valuer 接口來避免這個問題.sql
// 使用指針 type User struct { gorm.Model Name string Age *int } // 使用 Scanner/Valuer type User struct { gorm.Model Name string Age sql.NullInt64 // sql.NullInt64 實現了 Scanner/Valuer 接口 }
Select,指定你想從數據庫中檢索出的字段,默認會選擇所有字段。數據庫
db.Select("name, age").Find(&users) //// SELECT name, age FROM users; db.Select([]string{"name", "age"}).Find(&users) //// SELECT name, age FROM users; db.Table("users").Select("COALESCE(age,?)", 42).Rows() //// SELECT COALESCE(age,'42') FROM users;