我的数据库模型如下:
员工驾驶一辆或零辆车
车辆可以由一个或多个雇员驾驶
车辆具有模型类型,告诉我们其中的燃料类型.
我想要续集给我所有员工,他们不开车,或者如果他们这样做,那么车辆不是柴油车.
所以VehicleID为null或Vehicle.VehicleModel.IsDiesel = false
我目前的代码如下:
var employee = sequelize.define('employee', {
ID: Sequelize.INTEGER,
VehicleID: Sequelize.INTEGER
});
var vehicle = sequelize.define('vehicle', {
ID: Sequelize.INTEGER,
ModelID: Sequelize.INTEGER
});
var vehicleModel = sequelize.define('vehicleModel', {
ID: Sequelize.INTEGER,
IsDiesel: Sequelize.BOOLEAN
});
employee.belongsTo(vehicle);
vehicle.belongsTo(vehicleModel);
如果我运行以下内容:
options.include = [{
model: model.Vehicle,
attributes: ['ID', 'ModelID'],
include: [
{
model: model.VehicleModel,
attributes: ['ID', 'IsDiesel']
}]
}];
employee
.findAll(options)
.success(function(results) {
// do stuff
});
Sequelize做了一个左外连接来获取包含的表格.所以我找到了开车的员工而没有开车的员工.
一旦我添加了选项的位置:
options.include = [{
model: model.Vehicle,
attributes: ['ID', 'ModelID'],
include: [
{
model: model.VehicleModel,
attributes: ['ID', 'IsDiesel']
where: {
IsDiesel: false
}
}]
}];
Sequelize现在进行内部联接以获取包含的表.
这意味着我只会让那些开车的员工和车辆不是柴油车.不包括驾驶车辆的员工.
从根本上说,我需要一种方法来告诉Sequelize做一个左外连接,同时有一个where条件,表明连接表中的列是false或null.
编辑:
事实证明,解决方案是使用required:false,如下所示:
options.include = [{
model: model.Vehicle,
attributes: ['ID', 'ModelID'],
include: [
{
model: model.VehicleModel,
attributes: ['ID', 'IsDiesel']
where: {
IsDiesel: false
},
required: false
}],
required: false
}];
我已经尝试过把第一个’必需:假’但我错过了把内部的那个.我认为它不起作用所以我放弃了这种方法. Dajalmar Gutierrez的回答让我意识到我需要它才能发挥作用.