在这种特殊情况下,您可以采取一些解决方法来执行此特定查询,我想您有这些结构:
type Company struct {
TableName struct{} `sql:"companies"`
ID int64
Name string
Customers []*Customer `pg:",many2many:companies_customers"`
}
type Customer struct {
TableName struct{} `sql:"customers"`
ID int64
Username string
Companies []*Company `pg:",many2many:companies_customers"`
}
如果您只需要使用 执行查询,则JOIN
可以执行
var customers []*Customer
err := conn.Model(&customers).Column("customer.*").Join("inner join companies_customers cc on customer.id = cc.customer_id").Where("cc.company_id = ?", companyID).Select()
if err != nil {
// Error Handler
} else {
for _, customer := range customers {
fmt.Printf("Customer -> id: %d, username:%s \n", customer.ID, customer.Username)
}
}
这会产生:
SELECT "customer".* FROM customers AS "customer" inner join companies_customers cc on customer.id = cc.customer_id WHERE (cc.company_id = 1)
但是,您也可以执行以下操作:
var customers []*Customer
var company Company
err = conn.Model(&company).Column("Customers").Where("company.id = ?", companyID).Select()
if err != nil {
// error handler
} else {
customers = company.Customers
for _, customer := range company.Customers {
fmt.Printf("Customer -> id: %d, username:%s \n", customer.ID, customer.Username)
}
}
此代码执行两个查询:
SELECT "company"."id", "company"."name" FROM companies AS "company" WHERE (company.id = 1)
SELECT companies_customers.*, "customer".* FROM customers AS "customer" JOIN companies_customers ON (companies_customers."company_id") IN ((1)) WHERE ("customer"."id" = companies_customers."customer_id")
首先创建一个查询以从中获取数据company
,然后获取该公司的所有客户。