0
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

For the above query i use the following command

 userModel.find({ where: {user_id: 3}, include: [userVehicleModel] }).success(function(user){
    console.log(user)
})

It gives error:Possibly unhandled Error: user_vehicle is not associated to user!

Thanks in advance.

Gurpinder
  • 271
  • 3
  • 5
  • 11

2 Answers2

1

There's a good answer here.

Simple working solution:

'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);
    });
Community
  • 1
  • 1
srlm
  • 3,186
  • 2
  • 27
  • 40
0

For one to many associations in sequilize and to get record you just need to write this query.

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