繁体   English   中英

如何在书架中自我引用多对多关系

[英]How to do a Self-Referencing Many-to-Many Relationship in Bookshelf

我正在尝试在Bookshelf.Js中找出最明确和最正确的方法,为User模型建立多对多关系,以构建许多社交应用程序中存在的标准关注者/关注关系。 不过,Bookshelf中的文档让我陷入了困境。

我可以看到两种可能的方法:1)单独使用belongsToMany() ,或2)使用belongsToMany() throught() 两者都没有为我工作,但让我先告诉你我正在做些什么(1)。 我从这个模型设置开始:

const User = bookshelf.Model.extend({
  tableName: 'users',
  initialize: function() {
    this.on('creating', this.encryptPassword);
  },
  hasTimestamps: true,
  posts: function() {
    return this.hasMany(Posts, 'author');
  },
  comments: function() {
    return this.hasMany(Comments);
  },
  following: function() {
    return this.belongsToMany(UserFollow, 'users_users', 'follower_id', 'user_id');
  },
  followers: function() {
    return this.belongsToMany(UserFollow, 'users_users', 'user_id', 'follower_id');
  },
});

为了匹配我有一个knex迁移,添加了一个users_users表,如下所示:

exports.up = function(knex, Promise) {
  return knex.schema.createTable('users_users', (tbl) => {
    tbl.integer('user_id').references('users.id');
    tbl.integer('follower_id').references('users.id');
    tbl.unique(['user_id', 'follower_id']);  
      // This b/c I read a few places that Bookshelf might require a composite key.
  });
};

exports.down = function(knex, Promise) {
  return knex.schema.dropTable('users_users');
};

然后我有以下测试:

it('User model can record a follower', (done) => {
    const saveUsr = (data) => {
      return User.forge().save(data, {transacting: transaction});
    };
    Promise.all([saveUsr(mockUser), saveUsr(anotherMockUser)])
      .then((results) => {
        let usr1 = results[0];
        let usr2 = results[1];
        return usr2.followers().attach(usr1.id, {transacting: transaction});
      })
      .then((usrWithFollower) => {
        return usrWithFollower.fetch({
          withRelated: ['followers'],
          transacting: transaction
        });
      })
      .then((usr) => {
        console.log(JSON.stringify(usr));
        console.log('followers: ', usr.get('followers'));
        done();
      })
      .catch((err) => { done(err); });
   });

我在这里测试的并不多,因为我无法获得该功能,但是最后一个承诺中的JSON.stringify(user)的结果是回调如下:

[
   {
      "id":1,
      "name":"Sally Low",
      "username":"sally",
      "email":"sally@example.org",
      "created_at":"2016-06-05T15:24:41.835Z",
      "updated_at":"2016-06-05T15:24:41.835Z",
      "password":"$2a$10$613tL/baML9obsRN4Yg7MeU/2RiH7oK/nFUwfpQ1GYuA15VUFrFZu",
      "followers": [],
      "_pivot_user_id":2,
      "_pivot_follower_id":1
   }
]

正如你所看到的,看起来似乎已经设置了某种关系,因为有这些_pivot_道具,但它们对我来说并不清楚,而且我不确定为什么followers领域_pivot_回空洞。

如果有人能让我直截了当或以任何方式阐明情况,我会非常感激。

我认为那些UserFollow模型是User别名。 这不是必需的。

尝试添加Registry Plugin并将您的User模型编写为:

const User = bookshelf.Model.extend({
  tableName: 'users',
  // ...
  following: function() {
    return this.belongsToMany('User', 'users_users', 'follower_id', 'user_id');
  },
  followers: function() {
    return this.belongsToMany('User', 'users_users', 'user_id', 'follower_id');
  },
});
bookshelf.model('User', User);

attach()代码可以直接使用模型,不需要使用id

usr2.followers().attach(usr1);

我制作了模式的最小版本并尝试:

new User({name: 'Bia'}).
  fetch({withRelated: 'followers'}).
  then((m) => {console.log(m.toJSON());});

这让我回答:

{ name: 'Bia',
   id: 3,
   followers: 
    [ { id: 1, name: 'Ana', _pivot_user_id: 3, _pivot_follower_id: 1 },
      { id: 2, name: 'Mia', _pivot_user_id: 3, _pivot_follower_id: 2 } ] }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM