gpt4 book ai didi

mysql - Sequelize MySql 等效 ORM 查询

转载 作者:行者123 更新时间:2023-11-29 10:13:24 24 4
gpt4 key购买 nike

我有一个像这样的行查询

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;

最佳答案

我认为,您只需稍微修改一下 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'],
}]
})

关于mysql - Sequelize MySql 等效 ORM 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50553568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com