使用 GO/Beego 框架并尝试查询数据库以将一些记录加载到结构中。
Bellow是重要的代码:
type User struct {
UserId int64 `orm:"pk"`
FirstName string `orm:"null" valid:"MinSize(2);MaxSize(150)"`
LastName string `orm:"null" valid:"MinSize(2);MaxSize(150)"`
Email string `valid:"Required;MinSize(2);MaxSize(150);Email" required:"true" description:"user email address"`
Password string `valid:"Required;MaxSize(60)" required:"true" description:"user plain text password" json:"-"`
AccessLevel uint64 `json:"-"`
AuthKey string `json:"-"`
Status int `json:"-"`
DateAdded time.Time `orm:"-" json:"-"`
LastUpdated time.Time `orm:"-" json:"-"`
// relations
Profile *UserProfile `orm:"rel(one)" json:"-"` // OneToOne relation
}
type UserProfile struct {
UserId int64 `orm:"pk"` // doesn't work without a PK, doesn't make sense, it's a fk...
Company string `orm:"null" valid:"MinSize(2);MaxSize(150)"`
VatNumber string `orm:"null" valid:"MinSize(2);MaxSize(150)"`
Website string `orm:"null" valid:"MinSize(2);MaxSize(150)"`
Phone string `orm:"null" valid:"MinSize(2);MaxSize(150);Mobile"`
Address1 string `orm:"null" valid:"MinSize(2);MaxSize(255)"`
Address2 string `orm:"null" valid:"MinSize(2);MaxSize(255)"`
City string `orm:"null" valid:"MinSize(2);MaxSize(150)"`
State string `orm:"null" valid:"MinSize(2);MaxSize(150)"`
Zip string `orm:"null" valid:"MinSize(4);MaxSize(15)"`
Country string `orm:"null" valid:"MinSize(2);MaxSize(150)"`
ConfirmationKey string `orm:"null" valid:"Length(40)" json:"-"`
// relations
User *User `orm:"reverse(one)" json:"-"` // Reverse relationship (optional)
}
func GetAllUsers() []User {
o := orm.NewOrm()
var users []User
sql := `
SELECT user.*, user_profile.*
FROM user
INNER JOIN user_profile ON user_profile.user_id = user.user_id
WHERE 1`
_, err := o.Raw(sql).QueryRows(&users)
if err != nil {
beego.Error(err)
}
beego.Info(users)
return users
}
现在上面的问题是,在从 调用GetAllUsers()
嵌入结构时User
,即Profile
没有被填充,那么我将如何去让嵌入结构也被填充?
我也试图让用户:
o.QueryTable("user").Filter("status", STATUS_ACTIVE).RelatedSel("Profile").All(&users)
这会产生一个 sql 查询,如:
SELECT T0.`user_id`, T0.`first_name`, T0.`last_name`, T0.`email`, T0.`password`, T0.`access_level`, T0.`auth_key`, T0.`status`, T0.`profile_id`, T1.`user_id`, T1.`company`, T1.`vat_number`, T1.`website`, T1.`phone`, T1.`address1`, T1.`address2`, T1.`city`, T1.`state`, T1.`zip`, T1.`country`, T1.`confirmation_key` FROM `user` T0 INNER JOIN `user_profile` T1 ON T1.`user_id` = T0.`profile_id` WHERE T0.`status` = ? LIMIT 1000
而且我不知道它从哪里提出了 profile_id 列上的连接,因为它甚至不存在,而且我不确定如何指定要连接的正确列,似乎它是从结构名称中获取的。另外,我不喜欢没有办法指定选择什么的事实。
任何提示都非常感谢,我相信这是我想念的简单事情。
谢谢。