【问题标题】:Use JOIN in Sequelize在 Sequelize 中使用 JOIN
【发布时间】:2016-12-02 17:58:10
【问题描述】:

提示如何在 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';

谢谢!

【问题讨论】:

    标签: node.js postgresql join sequelize.js


    【解决方案1】:

    您需要为模型定义关联。 前任: 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/

    【讨论】:

      猜你喜欢
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多