Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build EXISTS clause in sequelize

Tags:

I have a model where there are 3 entities:

User Project Contributor 

A Project has a Owner (who is a User) and has multiple Contributors (who are Users). In my dashboard, I want to list a User's projects i.e. all Projects where the User is a Owner or a Contributor.

Finding owned projects using Project.findAll({where: [owner: user]}) is trivial. How do I modify this to find out the Projects where the user is also a contributor? This would (in the database query) translate to a sub-query using EXISTS clause.

like image 965
Venkat Avatar asked May 07 '15 06:05

Venkat


People also ask

How do you create a one to many relationship in Sequelize?

To create a One-To-Many relationship, the hasMany and belongsTo associations are used together; To create a Many-To-Many relationship, two belongsToMany calls are used together.

What is findByPk in Sequelize?

findByPk ​ The findByPk method obtains only a single entry from the table, using the provided primary key. const project = await Project. findByPk(123); if (project === null) {

How do you associate two models in Sequelize?

exports = function(sequelize, DataTypes) { var Session = sequelize. define("Session", { success: { type: DataTypes. BOOLEAN, allowNull: false, default: false }, TeammateId: { type: DataTypes. INTEGER, allowNull: false } }, { classMethods: { associate: function(models) { Session.


2 Answers

In general you can use exists clause in where like this:

Project.findAll({     where: {          $and:[sequelize.literal('exists (select 1 from "someTable" where ...)']     } }) 
like image 54
Ali Sherafat Avatar answered Sep 20 '22 13:09

Ali Sherafat


For example we define next associations:

Project.belongsToMany( User, {through: 'Contributor'} ); User.belongsToMany( Project, {through: 'Contributor'} );  Project.belongsTo( User, { as: 'Owner', foreignKey: 'owner'} ); 

If you want to find projects where the user is a contributor and the owner at the same time you can do it like this:

user.getProjects({ where: {owner: user.id} }); 
like image 27
stdob-- Avatar answered Sep 17 '22 13:09

stdob--