如何在 sequelize 查询的 where 中使用关系?
•浏览 1
How can I use a relation in the where of a sequelize query?
我有两张表,我们称它们为 \\'person\\' 和 \\'car\\',关系如下。一个人可以有 1 辆或 0 辆汽车。在后一种情况下,Car 表中将没有条目。
Person:
firstName,
lastName,
....
hasOne(Car, {
foreignKey: 'personId',
AS: 'personsCar'
})
Car:
personId,
colour,
...
belongsTo(Person, {
foreignKey: 'personId',
AS: 'carOwner'
})
Person.findAll({
include: [
model: Car,
AS: 'personsCar',
attributes: ['colour'],
],
WHERE: {
personsCar: {
[op.eq]: NULL,
},
},
})
Person.findAll({
include: [
model: Car,
AS: 'personsCar',
attributes: ['colour'],
WHERE: {
colour : 'green' // <---- YOUR COLOUR
},
],
})
Person:
firstName,
lastName,
....
hasOne(Car, {
foreignKey: 'personId',
AS: 'personsCar'
})
Car:
personId,
colour,
...
belongsTo(Person, {
foreignKey: 'personId',
AS: 'carOwner'
})
Person.findAll({
include: [
model: Car,
AS: 'personsCar',
attributes: ['colour'],
],
WHERE: {
personsCar: {
[op.eq]: NULL,
},
},
})
Person.findAll({
include: [
model: Car,
AS: 'personsCar',
attributes: ['colour'],
WHERE: {
colour : 'green' // <---- YOUR COLOUR
},
],
})
使用 Sequelize 我想从 Person 表中获取所有有"绿色"汽车或没有汽车的人
只是试图用以下任何颜色的汽车来找人会给出错误"列 Person.personsCar 不存在",我如何才能在查询的位置正确引用关系?
Person:
firstName,
lastName,
....
hasOne(Car, {
foreignKey: 'personId',
AS: 'personsCar'
})
Car:
personId,
colour,
...
belongsTo(Person, {
foreignKey: 'personId',
AS: 'carOwner'
})
Person.findAll({
include: [
model: Car,
AS: 'personsCar',
attributes: ['colour'],
],
WHERE: {
personsCar: {
[op.eq]: NULL,
},
},
})
Person.findAll({
include: [
model: Car,
AS: 'personsCar',
attributes: ['colour'],
WHERE: {
colour : 'green' // <---- YOUR COLOUR
},
],
})
你可以这样做:
Person:
firstName,
lastName,
....
hasOne(Car, {
foreignKey: 'personId',
AS: 'personsCar'
})
Car:
personId,
colour,
...
belongsTo(Person, {
foreignKey: 'personId',
AS: 'carOwner'
})
Person.findAll({
include: [
model: Car,
AS: 'personsCar',
attributes: ['colour'],
],
WHERE: {
personsCar: {
[op.eq]: NULL,
},
},
})
Person.findAll({
include: [
model: Car,
AS: 'personsCar',
attributes: ['colour'],
WHERE: {
colour : 'green' // <---- YOUR COLOUR
},
],
})