如何在sequelize中设置复杂的连接条件?

时间:2018-04-16 09:09:56

标签: node.js postgresql sequelize.js

我尝试使用sequelize将查询编码到数据库。这正是我想要的成绩单:

SELECT matches.uid_prop, matches.uid_player, matches.porcentaje, users.uid, profile_users.name, profile_users.profile, profile_users.birthday, profile_users.location
FROM (matches JOIN users ON (((matches.uid_prop = users.uid) AND (matches.uid_player = 11)) OR ((matches.uid_player = users.uid) AND (matches.uid_prop = 11)))) JOIN profile_users USING(uid)
WHERE (matches.uid_player = 11) OR (matches.uid_prop = 11);

我不知道是否应该更改关联以便按照我的意愿建立连接条件

Matches.belongsTo(User, {as: 'match_prop', foreignKey: 'uid_prop'});
User.hasMany(Matches, {as: 'user_prop', foreignKey: 'uid_prop'});

Matches.belongsTo(User, {as: 'match_player', foreignKey: 'uid_player'});
User.hasMany(Matches, {as: 'user_player', foreignKey: 'uid_player'});

或添加where并指定匹配和user之间的include的关系。如果是这种情况,我怎样才能引用来自用户制作的包含中的where语句的匹配字段,以便我可以比较,例如User.uid和Matches.uid_prop。 我尝试过这种符号,但它没有用:$ Matches.uid_prop $

Matches.findAll({
                attributes: ['porcentaje'],
                where: {
                    $or: [
                        {uid_prop: uid},
                        {uid_player: uid}
                    ]
                },
                include: [{
                    model: User,
                    attributes: ['uid'],
                    include: [{
                        model: Profile_user,
                        attributes: ['name', 'profile', 'birthday', 'location']
                    }]
                }]
            })

1 个答案:

答案 0 :(得分:2)

我认为您需要的只是required : true(内部联接),如:

Matches.findAll({
                    attributes: ['porcentaje'],
                    where: {
                        $or: [
                            {uid_prop: uid},
                            {uid_player: uid}
                        ]
                    },
                    include: [{
                        model: User,
                        attributes: ['uid'],
                        required : true , //<-------- HERE -------
                        include: [{
                            model: Profile_user,
                            attributes: ['name', 'profile', 'birthday', 'location']
                        }]
                    }]
                })

您的查询正在进行LEFT JOIN,要使其完全进入INNER JOIN,您可以使用required : true