简体   繁体   中英

sequelize - Where clause with associations

In sequelize I have boards and users setup, with a many to many association as follows

User.hasMany(Board, {through: BoardUsers});
Board.hasMany(User, {through:BoardUsers});

Is there anyway that, using a where clause I can find users that belong to one of a list of boards. For example, lets says I have 3 boards and I would like to find the first 20 users (using the default sort order) who belong to either board 1 or 3. Is there a way to do this without executing separate finds for each board, then manually combining the results.

I would love to be able to do something like:

User.findAll({where:{board: [1,3]}});

but I can't seem to find a way to do this.

As far as I can tell the equivalent SQL would be something like:

SELECT * FROM `users` WHERE id IN (SELECT userID FROM boardusers WHERE boardId IN (1,3))

But I would love to be able to do it through the ORM.

While I'm not sure if you can do this directly, you can always query for Boards and eagerly fetch users.

Something along these lines:

Board.findAll({where: {id: [1,3]}}, { include: [ User ] })

相当迟到的反应,但只是有同样的问题,这就是我如何让它在Sequelize 3.24.0中工作(类似这样);

User.findAll({ include: [{ model: Board, where: { $in: [1,3] }}] });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM