sequelize多条件_Sequelize:如何使用左外连接对连接表执行WHERE条件

My database model is as follows:

An employee drives one or zero vehicles

A vehicle can be driven by one or more employees

A vehicle has a model type that tells us it's fuel type amongst other things.

I'd like sequelize to fetch me all employees where they don't drive a vehicle, or if they do then the vehicle is not diesel.

So where VehicleID is null OR Vehicle.VehicleModel.IsDiesel = false

My current code is as follows:

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);

If I run the following:

options.include = [{

model: model.Vehicle,

attributes: ['ID', 'ModelID'],

include: [

{

model: model.VehicleModel,

attributes: ['ID', 'IsDiesel']

}]

}];

employee

.findAll(options)

.success(function(results) {

// do stuff

});

Sequelize does a left outer join to get me the included tables. So I get employees who drive vehicles and who don't.

As soon as I add a where to my options:

options.include = [{

model: model.Vehicle,

attributes: ['ID', 'ModelID'],

include: [

{

model: model.VehicleModel,

attributes: ['ID', 'IsDiesel']

where: {

IsDiesel: false

}

}]

}];

Sequelize now does an inner join to get the included tables.

This means that I only get employees who drive a vehicle and the vehicle is not diesel. The employees who don't drive a vehicle are excluded.

Fundamentally, I need a way of telling Sequelize to do a left outer join and at the same time have a where condition that states the column from the joined table is false or null.

EDIT:

It turns out that the solution was to use required: false, as below:

options.include = [{

model: model.Vehicle,

attributes: ['ID', 'ModelID'],

include: [

{

model: model.VehicleModel,

attributes: ['ID', 'IsDiesel']

where: {

IsDiesel: false

},

required: false

}],

required: false

}];

I had already tried putting the first 'required:false' but I missed out on putting the inner one. I thought it wasn't working so I gave up on that approach. Dajalmar Gutierrez's answer made me realise I needed both for it to work.

解决方案

When you add a where clause, sequelize automatically adds a required: true clause to your code.

Adding required: false to your include segment should solve the problem

Note: you should check this issue iss4019

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值