2 回答

TA貢獻1807條經(jīng)驗 獲得超9個贊
有一種方法可以在Gorm中使用多態(tài)的Haive One關(guān)系自然地做到這一點。這將使您能夠輕松運行@TheSphinX提供的一些查詢。
但是,您需要向關(guān)系表添加類型鑒別器列才能使其正常工作:
type Customer struct {
gorm.Model
Title string
Rel Relation `gorm:"polymorphic:Owner"`
}
type Company struct {
gorm.Model
Title string
Rel Relation `gorm:"polymorphic:Owner"`
}
type Relation struct {
gorm.Model
Foo string
OwnerID uint
OwnerType string
}
現(xiàn)在,您可以正常創(chuàng)建記錄:
cust := Customer{
Title: "Cust",
Rel: Relation{Foo: "bar"},
}
comp := Company{
Title: "Comp",
Rel: Relation{Foo: "baz"},
}
db.Create(&cust)
db.Create(&comp)
若要運行一個查詢,獲取客戶或公司以及@TehSphinX前兩個查詢中的相關(guān)信息,請執(zhí)行如下操作:
var cust Customer
db.Joins("Rel").First(&cust, 1)
最后一個查詢會更復(fù)雜,但也可以使用自定義行結(jié)構(gòu)和聯(lián)接來完成:
var rows []struct {
Relation
Customer Customer `gorm:"embedded;embeddedPrefix:cust_"`
Company Company `gorm:"embedded;embeddedPrefix:comp_"`
}
db.Select(`
relations.*,
customers.id AS cust_id,
customers.title AS cust_title,
companies.id AS comp_id,
companies.title AS comp_title
`).
Model(&Relation{}).
Joins("LEFT JOIN customers ON relations.owner_id = customers.id AND relations.owner_type = 'customers'").
Joins("LEFT JOIN companies ON relations.owner_id = companies.id AND relations.owner_type = 'companies'").
Find(&rows)
// now rows[i].Relation is filled, and rows[i].Customer or rows[i].Company
// are non-zero depending on rows[i].Relation.OwnerType

TA貢獻1995條經(jīng)驗 獲得超2個贊
注意:從純SQL的角度來說,因為我還沒有使用過:gorm
在我上面的評論中,我問:
您如何知道 中的 ID 是客戶 ID 還是公司 ID?您是否有一些布爾字段說這是不是客戶?還是 ID 本身包含該信息?喜歡和?CustomerOrCompanyIDcust-1234comp-1234
由于您需要一種方法來區(qū)分哪種ID,因此我建議使用兩個字段:和。其中之一始終是(或)。CustomerOrCompanyIDCustomerIDCompanyID0NULL
這樣,您就可以知道要聯(lián)接哪個表,也可以同時聯(lián)接兩者,具體取決于每行具有的數(shù)據(jù)類型,將填充客戶或公司的列。
我認(rèn)為如果有2個字段,應(yīng)該不會再有問題了,因為它會將它們中的每一個都處理為一個正常的關(guān)系,而不是為所有列設(shè)置。gorm
一些示例 SQL 語句 (MySQL Dialekt):
所有客戶:
SELECT
Relation.ID as RelID, Relation.OtherColumn,
Customer.ID, Customer.Name
/* etc. */
FROM
Relation INNER JOIN Customer ON (Relation.CustomerID=Customer.ID);
所有公司:
SELECT
Relation.ID as RelID, Relation.OtherColumn,
Company.ID, Company.Name
/* etc. */
FROM
Relation INNER JOIN Company ON (Relation.CompanyID=Company.ID);
您可能還希望所有數(shù)據(jù)都與“公司”和“客戶”列一起,并在前端決定使用哪些數(shù)據(jù):Relation
SELECT
Relation.ID as RelID,
Relation.OtherColumn,
Customer.ID as CustID,
Customer.Name as CustName,
Company.ID as CompID,
Company.Name as CompName,
/* etc. */
FROM
Relation
LEFT JOIN Company ON (Relation.CompanyID=Company.ID)
LEFT JOIN Customer ON (Relation.CustomerID=Customer.ID);
- 2 回答
- 0 關(guān)注
- 107 瀏覽
添加回答
舉報