简体   繁体   English

如何在gorm中链接连接?

[英]How to chain joins in gorm?

I want to write a query like我想写一个查询

SELECT table_a.*, table_c.* 
FROM table_a 
  LEFT JOIN table_b ON table_a.id = table_b.table_a_id
  LEFT JOIN table_c ON table_b.id = table_c.table_b_id
WHERE table_a.column_a = 'a_value',
  AND table_c.column_b = 'some_value'
  AND table_c.column_c = 'another_value';

EDIT: I missed out quite an important point in that the where clause variables are not fixed .编辑:我错过了非常重要的一点,即where 子句变量不是固定的 Depending on input, there may be more or fewer columns used for each table.根据输入,每个表可能使用更多或更少的列。

Currently, my query looks like目前,我的查询看起来像

db.Table("table_a").
    Joins("left join table_b on table_a.id = table_b.table_a_id").
    Joins("left join table_c on table_b.id = table_c.table_b_id").
    Select("table_a.*, table_c.*").
    Table("table_a").Where(map[string]interface{}{"column_a": "value"}).
    Table("table_c").Where(map[string]interface{}{
        "column_b": "some_value", 
        "column_c": "another_value",
    }).
    Find(&elem)

However, the logged SQL statement is但是,记录的 SQL 语句是

SELECT table_a.*, table_c.* 
FROM `table_c` # gorm gives the wrong starting table, should be table_a
  LEFT JOIN table_b ON table_a.id = table_b.table_a_id 
  LEFT JOIN table_c ON table_b.id = table_c.table_b_id 
WHERE (`table_c`.`column_a` = 'value') # wrong table again
  AND (`table_c`.`column_b` = 'some_value') 
  AND (`table_c`.`column_c` = 'another_value')

I'm not sure what's the issue here.我不确定这里有什么问题。 Is it that simultaneous queries for different tables isn't possible with this syntax?使用这种语法是否无法同时查询不同的表? I would prefer to avoid using the raw queries as much as possible.我宁愿尽可能避免使用原始查询。

UPDATE: I've tried dynamically generating the SQL where clause, but would prefer if there is a more straightforward way offered by gorm.更新:我尝试动态生成 SQL where 子句,但如果 gorm 提供更直接的方法,我会更喜欢。

You don't need to call this many Table methods.您不需要调用这么多Table方法。 It uses the last one that you've called to construct your SQL query.它使用您调用的最后一个来构建您的 SQL 查询。

Instead, once you have joined the tables, you can use them in the Where statements that come after the joins.相反,一旦您连接了这些表,您就可以在连接之后的Where语句中使用它们。

Try this:尝试这个:

db.Table("table_a").
    Joins("left join table_b on table_a.id = table_b.table_a_id").
    Joins("left join table_c on table_b.id = table_c.table_b_id").
    Select("table_a.*, table_c.*").
    Where("table_a.column_a = ?", "value").
    Where("table_c.column_b = ? AND table_c.column_c = ?", "some_value",  "another_value").
    Find(&elem)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM