gpt4 book ai didi

javascript - 如何在书架中建立自引用多对多关系

转载 作者:行者123 更新时间:2023-11-28 05:56:20 24 4
gpt4 key购买 nike

我正在尝试在 Bookshelf.Js 中找到最清晰、最“正确”的方式。为用户模型建立多对多关系,以构建许多社交应用程序中存在的标准关注者/被关注关系。不过,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); });
});

我在这里并没有真正进行太多测试,因为我无法让这个东西正常工作,但是最后一个 promise 中的 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 字段返回为空。

如果有人可以在这里纠正我或以任何方式阐明情况,我将非常感激。

最佳答案

我认为这些 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 } ] }

关于javascript - 如何在书架中建立自引用多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37644001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com