Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize LEFT JOIN only single column value

So I have next structure: Comments, Users, Likes.

Users has many likes, Comments has many likes.

I'm trying to get all Comments and check if User liked them. I have a raw query with LEFT JOIN that is working totally fine:

await sequelize.query(`SELECT comments.*, likes.liked FROM comments LEFT JOIN 
likes ON likes.commentId = comment.id AND likes.user_id = '123'`, {type: Sequelize.QueryTypes.SELECT});

I'm getting something like this:

    [{
        "id": 1,
        "userId": "123",
        "comment": "abcde",
        "liked": true
    },
    {
        "id": 2,
        "userId": "552",
        "comment": "abc",
        "liked": null
    }]

Now I'm trying to implement the same using findAll() method.

await Comment.findAll({
        include: [{
            model: Like,
            attributes: ['liked'],
            where: {user_id: id},
            required: false
        }]
    })

But I'm getting this:

[{
    "id": 1,
    "userId": "123",
    "comment": "abcde",
    "likes": [{liked:true}]
},
{
    "id": 2,
    "userId": "552",
    "comment": "abc",
    "likes": []
}]

So the question is: How can I include only column liked and not array of likes? Thank you.

like image 316
AliceAlice Avatar asked Oct 27 '25 03:10

AliceAlice


1 Answers

Relocate the attribute into the main model. Attributes from an included model are nested.... whereas the main model isn't. An example is below. You can add table name if the attribute name occurs in >1 table in the query.

await Comment.findAll({
   include: [{
     model: Like,
     attributes: [],   // attributes here are nested under "Like" 
     where: {user_id: id},
       required: false
     }],
   attributes: {
     include: [[Sequelize.col("liked"), "liked"]]  // NOT nested
   }
 })
like image 123
KenOn10 Avatar answered Oct 28 '25 17:10

KenOn10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!