Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query junction table without getting both associations in Sequelize

Consider the following models:

var User = sequelize.define('User', {
  _id:{
    type: Datatypes.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true
  },
  name: Datatypes.STRING,
  email:{
    type: Datatypes.STRING,
    unique: {
      msg: 'Email Taken'
    },
    validate: {
      isEmail: true
    }
  }
});

var Location= sequelize.define('Location', {
  _id:{
    type: Datatypes.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true
  },
  name: Datatypes.STRING,
  address: type: Datatypes.STRING
});

Location.belongsToMany(User, {through: 'UserLocation'});
User.belongsToMany(Location, {through: 'UserLocation'});

Is there a way to query the UserLocation table for a specific UserId and get the corresponding Locations. Something like:

SELECT * FROM Locations AS l INNER JOIN UserLocation AS ul ON ul.LocationId = l._id WHERE ul.UserId = 8

From what I can find you can do something similar to:

Location.findAll({
  include: [{
    model: User,
    where: {
      _id: req.user._id
    }
  }]
}).then( loc => {
  console.log(loc);
});

However, this returns the Locations, UserLocation junctions, and User which it is joining the User table when I do not need any user information and I just need the Locations for that user. What I have done is working, however, the query against the junction table is prefered instead of the lookup on the User table.

I hope this is clear. Thanks in advance.

Edit

I actually ended up implementing this in a different way. However, I am still going to leave this as a question because this should be possible.

like image 810
Justin Ober Avatar asked Apr 04 '16 07:04

Justin Ober


1 Answers

declaring junction table as separate class, something like this

var UserLocation = sequelize.define('UserLocation', {
  //you can define additional junction props here
});

User.belongsToMany(Location, {through: 'UserLocation', foreignKey: 'user_id'});
Location.belongsToMany(User, {through: 'UserLocation', foreignKey: 'location_id'});

then you can query junction table same as any other model.

like image 75
farincz Avatar answered Oct 09 '22 22:10

farincz