如何在 sequelize 中使用内连接
Posted
技术标签:
【中文标题】如何在 sequelize 中使用内连接【英文标题】:How to use inner joins in sequilize 【发布时间】:2015-04-02 08:03:54 【问题描述】:SELECT v.vehicle_id,v.vehicle_model_id,u.user_id,u.first_name FROM user u INNER JOIN user_vehicle v ON u.user_id= v.user_id WHERE u.user_id=3
对于上述查询,我使用以下命令
userModel.find( where: user_id: 3, include: [userVehicleModel] ).success(function(user)
console.log(user)
)
它给出错误:可能未处理错误:user_vehicle is not associated to user!
提前致谢。
【问题讨论】:
错误信息告诉你出了什么问题——两个模型没有关联。你在 sequelize 中设置了关联吗? 【参考方案1】:有一个很好的答案here。
简单的工作解决方案:
'use strict';
var Sequelize = require('sequelize');
var sequelize = new Sequelize(/*database*/'test', /*username*/'test', /*password*/'test',
host: 'localhost', dialect: 'postgres');
var User = sequelize.define('User',
firstName: type: Sequelize.STRING,
lastName: type: Sequelize.STRING
);
var Vehicle = sequelize.define('Vehicle',
brand: type: Sequelize.STRING
);
var firstUser;
User.hasMany(Vehicle, constraints: true);
Vehicle.belongsTo(User, constraints: true);
sequelize.sync(force: true)
.then(function ()
return User.create(firstName: 'Test', lastName: 'Testerson');
)
.then(function (author1)
firstUser = author1;
return Vehicle.create(UserId: firstUser.id, brand: 'Ford');
)
.then(function ()
return Vehicle.create(UserId: firstUser.id, brand: 'Toyota')
)
.then(function ()
return User.findAll(
where: id: 1,
include: [Vehicle]
);
)
.then(function displayResults(results)
results.forEach(function (c)
console.dir(c.toJSON());
);
)
.then(function ()
process.exit(0);
);
【讨论】:
【参考方案2】:对于 sequilize 中的一对多关联并获取记录,您只需要编写此查询。
let getuserId = req.query.user_id;
let foundUser await userModel.findOne(
where: user_id: getuserId ,
include: [ model: userVehicleModel ] )
);
if (foundUser) console.log(foundUser);
【讨论】:
以上是关于如何在 sequelize 中使用内连接的主要内容,如果未能解决你的问题,请参考以下文章
如何使用node.js控制sequelize中的内连接查询?
如何在使用 Sequelize 更改列或添加新列时更新迁移文件