Go GORM 预加载 & Select 只有符合预加载 table 条件的项目

Go GORM Preload & Select only items matching on preload table condition

我正在尝试使用 GORM select 仅来自父 table 且在相关 table 中具有匹配条件的项目。

type Table1 struct {
    gorm.Model
    Name string
    Email string
    Items Table2
}

type Table2 struct {
    gorm.Model
    Product string
    otherfield string
}

我想 return 将表 2 中的产品设置为特定值的所有表 1 项目。到目前为止,我得到了 mssql:无法绑定多部分标识符 "visits.sign_out_time"。很多。

我的命令是

var items []Table2
db.Debug().Preload("Table2").Where("table2.product = ?", "xxx").Find(&items).GetErrors()

不完全确定哪里出错了,但无论出于何种原因,.Where() 无法访问第二个预加载的 table。我该如何使用 GORM 来实现我想要做的事情?

谢谢, 亚历克斯

如果只想要Items,可以直接在Table2上查询,不需要预加载Table1

var items []Table2
db.Where("product = ?", "xxx").Find(&items).GetErrors()

或者您需要 Table1 的所有数据然后加入 table2 然后使用 where 子句

db.Debug().Joins("JOIN table2 ON table1.id = table2.table1_id")
          .Where("table2.product = ?", "xxxx").Find(&table1data)

这里我在Table2中没有看到任何外键,因为join.You可以添加一个。

type Table2 struct {
    gorm.Model
    Product  string
    Table1ID uint
}

Where("table2.product = ?", "xxx") 无法访问第二个(预加载的)table,因为 Preload 不是 JOINS,它是一个单独的 SELECT 查询。您的代码创建了两个单独的查询,如下所示:

// first query
SELECT * FROM table1 WHERE table2.product = 'xxx';
// second query
SELECT * FROM table2;

为了 return 所有 Table1Table2 中具有 Product 的记录设置为特定值,您必须执行以下操作:

var t1 []Table1
err = db.
Where(`EXISTS(SELECT 1 FROM table2 t2 WHERE t2.product = ? AND table1.id = t2.table1_id)`, productValue).
Find(&t1).Error

请注意,AND table1.id = t2.table1_id 部分只是两个 table 可能相关的示例,您可能有不同的关系,您需要相应地修改查询。

如果您希望 GORM 使用 Table2 数据填充 t1.Items,请在上述查询前添加 Preload("Items")