Sequelize MySql等效的ORM查询

时间:2018-05-27 15:12:57

标签: mysql node.js express sequelize.js

我有像这样的行查询

SELECT d.title
FROM DEALS d
LEFT JOIN USER u ON u.idUser = d.userId 
WHERE ((d.title LIKE  '%gouthamkrishna%' OR d.keywords LIKE  '%gouthamkrishna%')
OR CONCAT(u.firstName,'',u.lastName) LIKE  '%gouthamkrishna%') AND d.isPublic=1

我想基于它构建一个等效的ORM查询 这是我当前的查询

//deals table
const Deals = require('deals');
//user table
const User = require('user');
Deals.findAndCountAll({
        where:{
            isPublic:1,
            [Op.or]:[
                {title: { $like: '%' + params.keyword + '%' }},
                {keywords: { $like: '%' + params.keyword + '%' }}
            ]
       }, attributes:['title'],
       include:[
        {model:User, required:false,attributes:['firstName'],
        where:Sequelize.where(Sequelize.fn('concat_ws', Sequelize.col('firstName'), ' ', Sequelize.col('lastName')), {
                $like: '%' + params.keyword + '%'
                })

        }]

    })

但是这将返回空结果,但行查询返回结果

从ORM生成的等效查询

SELECT `DEALS`.`idDeal`, `DEALS`.`title`, `USER`.`idUser` AS `USER.idUser`, `USER`.`firstName` AS `USER.firstName` FROM `DEALS` AS `DEALS` LEFT OUTER JOIN `USER` AS `USER` ON `DEALS`.`userId` = `USER`.`idUser` AND concat_ws(`firstName`, ' ', `lastName`) LIKE '%gouthamkrishna%' WHERE (`DEALS`.`title` LIKE '%gouthamkrishna%' OR `DEALS`.`keywords` LIKE '%gouthamkrishna%') AND `DEALS`.`isPublic` = 1;

1 个答案:

答案 0 :(得分:1)

我认为,你需要稍微修改一下查询,试试这个:

Deals.findAndCountAll({
    where:{
            isPublic:1,
            [Op.or]:[
                {title: { $like: '%' + params.keyword + '%' }},
                {keywords: { $like: '%' + params.keyword + '%' }},
                Sequelize.where(Sequelize.fn('concat_ws', Sequelize.col('firstName'), ' ', Sequelize.col('lastName')), {
                    $like: '%' + params.keyword + '%'
                })
            ]
    }, 
    attributes:['title'],
    include:[
        {
            model:User, 
            required:false,
            attributes:['firstName'],
    }]
})