Reputation: 415
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.
Upvotes: 4
Views: 5420
Reputation: 1968
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
}
})
Upvotes: 6