[英]Sequelize include nested column: Unknown column in 'where clause'
我正在嘗試使用 Sequelize ORM 的功能,該功能允許從包含的模型中引用嵌套列(請參閱Sequelize Docs: Complex where clauses at the top-level )。 在文檔中指出,我可以使用$nested.column$
語法。
以下是我正在嘗試做的事情:
let where = { memberId };
if (req.query.search) {
const like = { [Op.like]: `%${req.query.search}%` };
where = {
...where,
[Op.or]: [
{ '$bookItem.serial$': like },
{ '$bookItem.book.name$': like },
{ '$bookItem.book.ISBNCode$': like },
],
};
}
const options = {
where,
include: [
{
model: models.BookItem,
as: 'bookItem',
required: false,
include: [
{
model: models.Book,
as: 'book',
attributes,
required: false,
},
],
},
],
});
const transactions = await models.Borrow.findAll(options);
但是,對於上面的代碼,我收到以下錯誤:
"Unknown column 'bookItem.serial' in 'where clause'"
我錯過了什么?
bookitem
是一個表嗎? 還是數據庫?
bookItem.serial
代表db.tbl
或tbl.column
bookItem.book.name
只能代表db.tbl.column
既然bookItem
好像是數據庫名,那么serial
肯定是表名。 此時,“tablename LIKE...”是一個語法錯誤。
在您的鏈接文檔中 books has no name column,將$bookItem.book.name$
更改為$bookItem.book.title$
,然后嘗試在required: false
下面添加right: true
以創建內部聯接。
我已經在我這邊糾正了這個錯誤。 最初,我正在寫這個查詢
但現在我重新排列了查詢並且它有效
錯誤查詢
let where = {
[op.and]: [
{ id: partner_id },
{ [op.or]: [
{ '$customers.customer_name$': { [op.like]: '%' + query + '%'} },
{ '$customers.email$': { [op.like]: '%' + query + '%'} },
]},
],
};
// const where = {
// id: partner_id
// }
return await this.deliveryBoys.findOne({
attributes: [
['id', 'partner_id'],
'delivery_boy_name',
'email',
'profile_picture',
'phone_number',
'fcm_token',
],
include: [
{
model: this.customers,
as: 'customers',
attributes: ['id', 'customer_name', 'email', 'profile_picture', 'phone_number'],
require: true,
where: {
customer_name: {
[op.like]: '%' + query + '%'
}
},
include: [
{
model: this.company,
as: 'company',
},
{
model: this.address,
as: 'address',
required: false,
where: {
status: 1
}
}
]
},
],
where,
});
let where = {
[op.and]: [
{ '$deliveryBoys.id$': partner_id },
{ [op.or]: [
{ '$customers.email$': { [op.like]: '%' + query + '%'} },
{ '$customers.customer_name$': { [op.like]: '%' + query + '%'} },
{ '$customers.phone_number$': { [op.like]: '%' + query + '%'} },
{ '$company.name$': { [op.like]: '%' + query + '%'} },
]},
],
};
return await this.customers.findAll({
attributes: ['id', 'customer_name', 'email', 'profile_picture', 'phone_number'],
include:[
{
model: this.deliveryBoys,
as: 'deliveryBoys',
attributes: ['id','delivery_boy_name','phone_number','email','profile_picture','status',],
where:{
id: partner_id
}
},
{
model: this.company,
as: 'company',
},
{
model: this.address,
as: 'address',
required: false,
where: {
status: 1
}
}
],
where
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.