-
Notifications
You must be signed in to change notification settings - Fork 568
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Self-Referencing Many-to-many Relation for followers/followed relationship #1276
Comments
@ezmiller I guess it is a mixup of your otherKey and foreignKey identifiers. 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', 'user_id', 'follower_id');
},
followers: function() {
return this.belongsToMany(UserFollow, 'users_users', 'follower_id', 'user_id');
},
}); |
Initally a reply to deleted comment by @ahmedcanuck
@ahmedcanuck I prefer to think that for the current case polymorphic relationship is redundant. @ezmiller's solution is elegant enough. |
Current specification of belongsToMany has a bug. Its `otherKey` and `foreignKey` parameter description are mistakenly partially swapped. Many issues have come up because of this problem. eg. bookshelf#397, bookshelf#1031, bookshelf#1276
Closing as resolved by #1288 |
Hi All, I'm trying to work out the most expressively clear and "correct" way of setting up a many-to-many relationship for a User model to build-out the standard followers/followed relationship that exists on many social applications.
I can see two possible approaches: 1) Using
belongsToMany()
alone, or 2) UsingbelongsToMany()
with athrought()
. Neither have worked for me, but let me show you first what I'm doing for (1). I start with this Model setup:And to match that I have a knex migration that adds a
users_users
table like so:Then I have the following test:
I'm not really testing much here as I've not been able to get the thing, working, but the result of
JSON.stringify(user)
in the last promise then callback is the following:As you can see, it looks as if some sort of relation has been setup here given that there are these
_pivot_
props, but what they are is not clear to me, and I'm not sure why thefollowers
field is coming back empty.If anyone can set me straight here or illuminate the situation in any way, I'd be much obliged.
The text was updated successfully, but these errors were encountered: