我有3张桌子代表我的多对多关系。客户,公司,公司_客户。
companies:
- id
- name
customers:
- id
- username
companies_customers:
- id
- customer_id
- company_id
现在我要运行的查询是选择company_id为1的所有客户。原始SQL查询可能/可能看起来像这样:
SELECT * FROM customers c INNER JOIN customers_companies cc ON c.id = cc.customer_id WHERE cc.company_id = 1
我试过在go-pg中做这样的事情:
var customers []*Customer
s.DB.Model(&customers).Relation("Companies", func(q *orm.Query) (*orm.Query, error) {
return q.Where("company_id = ?", companyID), nil
}).Select()
答案 0 :(得分:1)
在这种特殊情况下,你可以做一些变通方法来执行这个特定的查询,我想你有这些结构:
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
获取数据,然后获取该公司的所有客户。