Sequelize MySql equivalent ORM query

蹲街弑〆低调 提交于 2019-12-11 17:39:59

问题


I have a row query like this

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

I want to build an equivalent ORM query based on it Here is my current query

//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 + '%'
                })

        }]

    })

But this will return the empty result however the row query returns result

the equivalent query generated from 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:


I think , you need to just modify where query a bit , try this :

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


来源:https://stackoverflow.com/questions/50553568/sequelize-mysql-equivalent-orm-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!