我在理解如何使用 gorm 獲取相關資訊時遇到問題。這是我第一次主動使用 ORM。
我正在嘗試獲取特定用戶 ID 有權訪問的所有設備。使用當前功能,我可以獲得所有設備,不僅是屬于實際用戶 ID 的設備,還包括該設備所屬的用戶串列,這是我目前真正不需要的資訊。
有沒有辦法使用 gorm 使用 user_devices 連接表獲取用戶可以訪問的設備,或者這是我應該創建自定義查詢以實作我想要的東西?
謝謝你。
type User struct {
ID uint
Name string
Email string
Age uint8
Birthday time.Time
Password string
ActivatedAt time.Time
OrgID uint
Org Org
Devices []Device `gorm:"many2many:user_devices"`
CreatedAt time.Time
UpdatedAt time.Time
}
type Device struct {
ID uint
Name string
Hwaddr string
OrgID uint
PublicIP uint
Org Org
Users []User `gorm:"many2many:user_devices"`
DeviceType string
Identity string
LastPolledAt time.Time
CreatedAt time.Time
UpdatedAt time.Time
}
func (u *Device) FindAllDevicesByUid(db *gorm.DB, user *User) (*[]Device, error) {
var err error
devices := []Device{}
err = db.Debug().Preload("Users", "user_id = ?", user.ID).Find(&devices).Error
if err != nil {
return &[]Device{}, err
}
return &devices, err
}
結果:
{
"ID": 4,
"Name": "Test 4",
"Hwaddr": "00:00:00:00:00:04",
"OrgID": 1,
"PublicIP": 0,
"Org": {
"Id": 0,
"Name": "",
"Users": null,
"CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z"
},
"Users": [
{
"ID": 1,
"Name": "Jan Astrup",
"Email": "[email protected]",
"Age": 0,
"Birthday": "0001-01-01T00:00:00Z",
"ActivatedAt": "2022-04-24T15:48:40 02:00",
"OrgID": 1,
"Org": {
"Id": 0,
"Name": "",
"Users": null,
"CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z"
},
"Devices": null,
"CreatedAt": "2022-04-24T15:48:40 02:00",
"UpdatedAt": "2022-04-24T15:48:40 02:00"
}
],
"DeviceType": "Router",
"Identity": "M1923 4",
"LastPolledAt": "0001-01-01T00:00:00Z",
"CreatedAt": "2022-04-24T15:17:30 02:00",
"UpdatedAt": "2022-04-24T15:17:30 02:00"
}
uj5u.com熱心網友回復:
要僅為特定用戶加載設備,您可以使用該Joins功能來連接表user_devices和devices.
devices := []Device{}
err = db.Debug().Joins("JOIN user_devices ud ON ud.device_id = devices.id").Where("ud.user_id = ?", user.ID).Find(&devices).Error
除此之外,您始終可以加載用戶并預加載其設備:
u := User{}
err = db.Debug().Preload("Devices").First(&u, user.ID).Error
然后,您可以使用u.Devices回傳用戶的設備,但我認為這種方法執行兩個查詢來獲取用戶的設備。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/463927.html
上一篇:Go模板中的浮點除法
