我有两张表,其中一张表具有另一张表的 ID。1:1 关系。所以像
EventFeedback
somePrimaryKey
userEventID
UserEvent
userEventID
Run Code Online (Sandbox Code Playgroud)
Sequalize 的关系定义为
models.UserEvent.hasOne(models.EventFeedback, { foreignKey: 'userEventID' });
Run Code Online (Sandbox Code Playgroud)
我需要的所有条目UserEvent没有一个条目EventFeedback,这是一个排他性的加入。从这篇文章中窃取图像,因为它们有很好的个人图像:
他们甚至给出了示例代码!
SELECT <select_list>
FROM Table_A A
LEFT JOIN Table_B B
ON A.Key = B.Key
WHERE B.Key IS NULL
Run Code Online (Sandbox Code Playgroud)
我如何在续集中做到这一点?我是否只需要进行左连接并手动处理它?
pio*_*ias 10
You need to eager load EventFeedback when querying UserEvent and add proper where clause. You also need to define that EventFeedback is not required in the result so the query will generate LEFT JOIN instead INNER JOIN
UserEvent.all({
include: [
model: EventFeedback,
required: false, // do not generate INNER JOIN
attributes: [] // do not return any columns of the EventFeedback table
],
where: sequelize.where(
sequelize.col('EventFeedback.userEventID'),
'IS',
null
)
}).then(userEvents => {
// user events...
});
Run Code Online (Sandbox Code Playgroud)
In the code above the sequelize is an instance of Sequelize with model defined in it. You can also refer to the documentation of sequelize.where() and sequelize.col() methods.
| 归档时间: |
|
| 查看次数: |
4182 次 |
| 最近记录: |