仅对 LEFT JOIN 单列值进行序列化

Ali*_*ice 2 mysql node.js sequelize.js

所以我有下一个结构:评论、用户、喜欢。

用户有很多喜欢,评论有很多喜欢。

我正在尝试获取所有评论并检查用户是否喜欢它们。我有一个带有 LEFT JOIN 的原始查询,它完全正常工作:

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});
Run Code Online (Sandbox Code Playgroud)

我得到这样的东西:

    [{
        "id": 1,
        "userId": "123",
        "comment": "abcde",
        "liked": true
    },
    {
        "id": 2,
        "userId": "552",
        "comment": "abc",
        "liked": null
    }]
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试实现相同的 usingfindAll()方法。

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

但我得到这个:

[{
    "id": 1,
    "userId": "123",
    "comment": "abcde",
    "likes": [{liked:true}]
},
{
    "id": 2,
    "userId": "552",
    "comment": "abc",
    "likes": []
}]
Run Code Online (Sandbox Code Playgroud)

所以问题是:我怎样才能只包含列liked而不是数组likes?谢谢你。

小智 5

将属性重定位到主模型中。来自包含模型的属性是嵌套的......而主模型不是。下面是一个例子。如果属性名称出现在查询中的 >1 个表中,您可以添加表名称。

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
   }
 })
Run Code Online (Sandbox Code Playgroud)