为多对多关系构建 go-pg ORM 查询

Building go-pg ORM query for many to many relationship

我有 3 个表来表示我的多对多关系。客户,公司,companies_customers。

companies:
 - id
 - name

customers:
 - id
 - username

companies_customers:
 - id
 - customer_id
 - company_id

现在我想要 运行 的查询是 select 所有 company_id 为 1 的客户。原始 SQL 查询 could/might 看起来像这样:

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()

在这种特殊情况下,您可以采取一些变通方法来执行此特定查询,我想您有以下结构:

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 获取数据,然后获取该公司的所有客户。