如何在sequelize中使用内连接

时间:2015-02-03 07:36:50

标签: mysql node.js sequelize.js

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未与用户关联!

提前致谢。

2 个答案:

答案 0 :(得分: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);
    });

答案 1 :(得分:0)

对于一对多的关联并获取记录,您只需要编写此查询即可。

let getuserId = req.query.user_id;
let foundUser await userModel.findOne({ 
      where: {user_id: getuserId },
      include: [ { model: userVehicleModel } ] })
 });
 if (foundUser) console.log(foundUser);