Return 存在数据透视条目的模型

Return model where the pivot entry exists

我正在使用 BookshelfJS。我有两个模型 usersposts。显然,这里的关系是多对多的。所以我有一个支点 table post_user

现在,给定一个 user_id,我想找到该用户的所有 posts。到目前为止,我已经设法使用 knex:

做到了这一点
knex.select()
    .from('post_user')
    .where('user_id', user_id)
    .then(function (pivots) {
        // Now loop through pivots and return all the posts
        // Using pivot.post_id
        pivots.map(function(pivot) {})
    });

有更简洁的方法吗?

您需要在 Bookshelf 模型中定义多对多关系。像这样:

var User = bookshelf.Model.extend({
  tableName: 'users',
  posts: function() {
    return this.belongsToMany(Post);
  }
});

var Post = bookshelf.Model.extend({
  tableName: 'posts',
  users: function() {
    return this.belongsToMany(User);
  }
});

按照惯例,枢轴 table Bookshelf 将使用 posts_users(table 名称与 _ 组合,从 table 开始按字母顺序排在第一位)。它应该包含一个 user_id 和一个 post_id (以及这两者的复合 PK)。如果您不想重命名枢轴 table,请参阅 documentation for belongsToMany 以获取有关如何定义枢轴 table 和 ID 的说明 table。

之后,您可以使用 Bookshelf 查询您的模型:

return new User().where('id', user_id)
    .fetch({withRelated: 'posts'})
    .then(function (user) {
       var postCollection = user.get('posts');
       // do something with the posts
    });

另请参阅 fetch 的文档。