簡體   English   中英

建立多對多關系的go-pg ORM查詢

[英]Building go-pg ORM query for many to many relationship

我有3張桌子代表我的多對多關系。 客戶,公司,company_customers。

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

在這種情況下,您可以做一些變通辦法來執行此特定查詢,我想您具有以下結構:

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獲取數據,然后,獲取該company的所有客戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM