提示如何在Sequelize中使用JOIN? 我有以下代码:
db.User.findAll({
attributes: ['id'],
where: {vipEnd: {lt: expiresVip}, vip: true},
limit: 100,
order: 'id'
}).then(function(users) {
就4而言,它看起来像这样:
SELECT "vkId" AS "id"
FROM "user" AS "user"
WHERE "user"."vipEnd" < 1469699683 --expiresVip
AND "user"."vip" = true
ORDER BY id
LIMIT '100';
如何实现这样的结果?
SELECT "vkId" AS "id"
FROM "user" AS "user"
LEFT JOIN "notification" ON "notification"."userId" = "user"."vkId"
WHERE "user"."vipEnd" < 1469699683
AND "user"."vip" = true
AND "notification"."type" = 4
AND "notification"."expiresVipDate" < 1469699683
ORDER BY id
LIMIT '100';
谢谢!
答案 0 :(得分:2)
您需要定义模型的关联。
例如:
db.User.hasMany(db.Notification, {foreignKey: 'UserId'});
使用属性包括在sequelize中:
db.User.findAll({
include: [{
model: db.Notification,
required: true//true INNER JOIN, false LEFT OUTER JOIN - default LEFT OUTER JOIN
}]}).then(function(user) {}, function(err) {
res.json(err, 400);});
您应该在这里咨询更多 http://docs.sequelizejs.com/en/latest/docs/associations/