如何使用bookshelf ORM中的withRelated属性从多个表中获取嵌套数据?

时间:2016-11-09 16:09:46

标签: mysql node.js express bookshelf.js

我有三张桌子(post_like,user,posts)。我正在使用关系来捕获喜欢特定帖子的用户的姓名。我收到了user_id,但我无法获取用户名。

var post = Bookshelf.Model.extend({
    tableName: 'posts',
    hasTimestamps: true,
    postLike: function() {
        return this.belongsToMany(post);
    }
});


var postLike = Bookshelf.Model.extend({
    tableName: 'posts_like',
    hasTimestamps: true,
    post: function() {
        return this.belongsTo(post);
    },
    user: function() {
        return this.belongsTo(user);
    }
});

var user = Bookshelf.Model.extend({
    tableName: 'users',
    hasTimestamps: true,
    post: function() {
        return this.hasMany(post);
    },
    postLike: function() {
        return this.belongsToMany(postLike);
    }
});

我收到了这样的回复

    posts:{
        id:XXX,
        summary:XXX,
        author:{
            name: XXX,
            bio:XXX
        },
        like:[{
            user_id:XXX
        },
        {
            user_id:XXX
        }]
  }

我需要这样的东西

posts:{
            id:XXX,
            summary:XXX,
            author:{
                name: XXX,
                bio:XXX
            },
            like:[{
                user_id:XXX,
                user:{
                    name:XXX
                }
            },
            {
                user_id:XXX,
                user:{
                    name:XXX
                }
            }]
      }

0 个答案:

没有答案