Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize: Check and add BelongsToMany (N to N) relation

My application got many Users who can like many Posts (N to N). That's why I assigned the following "belongsToMany" Relations for my Models (Sequelize Doc):

// Post Model
models.Post.belongsToMany(models.User, { through: models.PostLikes});

// User Model
models.User.belongsToMany(models.Post, { through: models.PostLikes});

Inside my Post Controller I got the following use case for the "likePost" function:

  1. Check if the Post exists. (seems to work)
  2. If so, check if the User already liked this Post.
  3. If not, assign the N to N relation between User and the Post. (seems to work)

    // User likes Post
    exports.likePost = async (req, res) => {
     const postToLike = await Post.findById(req.body.postId);
     // Check if the Post exists
     if (!postToLike) {
      return res.status(404).json({ error: { message: 'Post not found.' }});
     }
    
     // Did user already like the post?
     // HERE IS THE NOT WORKING PART:
     if (await req.user.hasPost(postToLike).isFulfilled()) {
      return res.status(422).json({ error: { message: 'Already liked post.' }});
     }
    
     // add Like
     await req.user.addPost(postToLike);
     return res.send(postToLike);
    };
    

Now I got the Problem, that I am not able to check if a User already liked a Post. "req.user.hasPost(postToLike).isFulfilled()" always returns false, even if indeed I can see the correct relation in my "PostLikes" DB Table. So how can I correctly:

  1. Check if a User already liked a Post.
  2. Assign this relation.
  3. And remove the relation with Sequelize?

BTW this is how my PostLikes Table looks like:

+----+--------+--------+
| id | userId | postId |
+----+--------+--------+
|  1 |      2 |      3 |
+----+--------+--------+
like image 599
HelloWorld0815 Avatar asked Mar 24 '18 13:03

HelloWorld0815


People also ask

How do I use belongsToMany in Sequelize?

You need to call the belongsToMany() method and pass the junction table using the through option as shown below: Student. belongsToMany(Class, { through: Enrollment }); Class. belongsToMany(Student, { through: Enrollment });


1 Answers

Looking at the documentation, there is no mention of isFulfilled(). Did you try to do req.user.hasPost(postToLike) ? (Sequelize Doc)

like image 175
chettyharish Avatar answered Sep 21 '22 13:09

chettyharish