sequelize mysql等价orm查询

igetnqfo  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(310)

我有这样一个行查询

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;
ki0zmccv

ki0zmccv1#

我想,你只需要修改一下where查询,试试这个:

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'],
    }]
})

相关问题