我有以下要求:
select bo.id, bo.code, bo.title from books bo, Chapters c, Blocks bk
where (bo.id=c.id and c.idChapter=bk.idChapter) and ( (bo.title like '%intermit%') or (bk.content like '%intermit%') )
group by bo.code
order by bo.code asc
我尝试使用Sequelize翻译请求:
db.books.findAll({
attributes: ['id', 'title', 'code'],
include: [
{
model: db.chapters,
as: 'Chapters',
attributes: [ 'id', 'idChapter' ],
include: [
{
model: db.blocks,
as: 'Blocks',
attributes: ['content', 'idBlock'],
where: {content: {[Op.like]: ('%'+criteria+'%') }}
}
]
}
],
where: {title: {[Op.like]: ('%'+criteria+'%') }},
group: ['code'],
order: [['code', 'ASC']]
})
由Sequelize生成的请求并不完全相同。它使用join
而不是where
子句,但这不是问题。
问题是关于字段blocks.content的where
子句。低于Sequelize生成的请求(安静简化,易于阅读)。
SELECT bo.id, bo.title, bo.code
FROM books AS bo
LEFT OUTER JOIN ( Chapters AS c INNER JOIN Blocks AS bk ON c.idChapter = bk.idChapter AND bk.content LIKE '%intermit%') ON bo.id = c.id
WHERE bo.title LIKE '%intermit%' GROUP BY bo.code ORDER BY bo.code ASC;
与字段where
有关的content
子句放在inner
子句的内部。它应位于主要where
子句的外部。对于该请求,结果是不同的,而不是预期的结果。
我尝试用单个where
条款修改代码:
where: { [Op.or]: [ {title: {[Op.like]: ('%'+criteria+'%')}}, {content: {[Op.like]: ('%'+criteria+'%')}} ] },
但是它无法识别字段content
,因为Sequelize希望在表books
中找到它。
我该如何解决我的问题?