我是ORM(和GORM)的新手,如果这是一个明显的问题,我深表歉意,但文档中似乎没有涉及到这一点.
我将以examples from the documentation分为基础回答我的问题
问题1:属于
// `User` belongs to `Company`, `CompanyID` is the foreign key
type User struct {
gorm.Model
Name string
CompanyID int
Company Company
}
type Company struct {
ID int
Name string
}
-
User
只属于一个Company
→ 这是由代码处理的 -
Company
有很多User
→ is this implied by the code above?或者我应该以某种方式在Company
中添加一个关系O2M?
问题2:有很多
// User has many CreditCards, UserID is the foreign key
type User struct {
gorm.Model
CreditCards []CreditCard
}
type CreditCard struct {
gorm.Model
Number string
UserID uint
}
-
User
等于1+CreditCard
→ 这是由代码处理的 - A
CreditCard
can belong to several users (say, a shared family CC) → is it implied? (if not: how to set up the O2M relationship).
Or is it, instead, a case where aCreditCard
is explicitly configured to belong to only one user?