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.
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.
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) {
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.
In general you can use exists
clause in where
like this:
Project.findAll({ where: { $and:[sequelize.literal('exists (select 1 from "someTable" where ...)'] } })
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} });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With