如何在有条件的情况下在Sequelize中使用LEFT JOIN?

时间:2018-07-24 06:54:52

标签: mysql sql sequelize.js

关系:

import {Topics, Users} from './model-sequelize';
Users.hasMany(Topics, {foreignKey : 'UserID'});
Topics.hasOne(Users, {foreignKey : 'UserID'});

getAllTopics (params, cb) {
    const {PageIndex, PageSize} = params;
    const pg = paging(PageIndex, PageSize)
    Topics.findAll({
        offset: pg.offset,
        limit: pg.limit,
        attributes: {
            exclude: ['IsDelete']
        },
        include:[
            {
                model:Users,
                attributes: ['UserName', 'UserID'],
                required:false
            }
        ],
        where: {
            IsDelete: 0
        },
        order: [[Sequelize.col('LastReplyTime'), 'DESC']]
    }).then(res => {
        cb(null, res)
    }).catch(err => {
        cb(err)
    })
}

SQL是:

SELECT `topics`.`TopicReplies`, 
       `topics`.`TopicHits`, 
       `topics`.`TopicName`, 
       `topics`.`TopicLabel`, 
       `topics`.`LastReplyUserId`, 
       `topics`.`LastReplyTime`, 
       `topics`.`UserID`, 
       `topics`.`TopicContent`, 
       `topics`.`Plate`, 
       `topics`.`ID`, 
       `topics`.`createdAt`, 
       `topics`.`updatedAt`, 
       `user`.`ID` AS `user.ID`, 
       `user`.`UserName` AS `user.UserName`, 
       `user`.`UserID` AS `user.UserID` 
FROM `topics` AS `topics` 
LEFT OUTER JOIN `users` AS `user` ON `topics`.`ID` = `user`.`UserID` 
WHERE `topics`.`IsDelete` = 0 
ORDER BY `LastReplyTime` DESC LIMIT 20, 10;

enter image description here

条件为topicsID = userUserID

问题

我想使用“ ON topicsUserID = userUserID

现在结果没有用户表的数据。我该怎么办?

1 个答案:

答案 0 :(得分:0)

我认为您在关联上有疑问:

更改此:

Topics.hasOne(Users, {foreignKey : 'UserID'});

收件人:

Topics.belongsTo(Users, {foreignKey : 'UserID'});

然后重试。