You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@janmeier, why no for N:1 such as in my previous exemple, I need this in a real world exemple:
Operations.belongsTo(User)Operations.hasMany(Breakdowns)/* There is no way to define this relation without adding a field to the breakdown, but I will have to manually sync operation.userId and breakdown.userId */Breakdowns.belongsTo(User)
A user have multiple operations, an operation have multiple breakdowns, but: a breakdown and an operation have only one same user. The operation works as a join table between one breakdown and one user.
I now that I can store the userId in the breakdown AND in the operation but I will have to maintain the userId fields (ie operation.userId === breakdown.userIdalways).
beforeCreate(breakdown){if(!breakdown.operationId)thrownewError('Unable to create breakdown without operation.');/* Attach owner to breakdown. */if(!breakdown.ownerId){returnbreakdown.getOperation().then(function(operation){if(!operation||!operation.ownerId)thrownewError('Unable to retrieve owner from operation.');breakdown.ownerId=operation.ownerId;});}},
@mickhansen yep, but that's mean that if you fetch the user's breakdown, you'll fetch, for each breakdown, the operation. That's not very efficient. Something like:
{include: [{model: Operation,fetch: false,// Search for a condition in nested models, but do not eager load.where: {userId: userId}}
would be very usefull.
note: that's not so good when you have a breakdown instance and you need the user. You have to fetch the operation.
@verdier You can disable attributes on the join with include.attributes = [].
Yes we'd be open to a pull request :)
The argument to through should maybe be an Association rather than a Model, for less ambiguity, not sure.
@mickhansen I just find the name belongsToMany so confusing. The difference between hasMany and belongsToMany is not clear at all.
n:m in other languages:
Ruby calls n:m relations has_and_belongs_to_many, that makes it more clear that it is basically hasMany, but both ways.
Doctrine (PHP) uses @hasMany on both models with mappedBy and inversedBy parameters. The join table is set through @JoinTable.
Hibernate uses many-to-many columns on both models that both specify the same join table name table
I define my n:m relations in Sequelize in a similar way to the above:
@felixfbecker We actually have hasAndBelongsToMany as an alias for belongsToMany.
I understand your issue, but i don't think it's something we're likely to change right now, i prefer N:M being a seperate call from 1:M
If we think it's confusing, maybe make hasAndBelongsToMany the main name listed in the docs with belongsToMany as the alias, rather than the other way around?
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂
A Referrer can have any number of Referral Programs that can have any number of Referrals.
A Referral can only belong to one Referral Program which can only belong to one Referrer.
A Referral can only belong to one Referrer through a Referral Program.
@verdier OK this magically ✨ work's for me, @mickhansen@janmeier could any of you please explain why maybe it's already implemented there and useful I've seen a lot of requests for that feature.
even though the option through is not possible in belongsTo I've tried it and what makes it work that I've passed also foreignKey: 'id' which refers to the A FK in the join table C
// A --> B --> C
C.belongsTo(A, {
through: B,
foreignKey: 'id',
})
if this has no unexpected behavior, the next step is how do we assign even more far nested joins like it
.ie
// A --> B --> C --> D
D.belongsTo(A, {
... how ?
})
@ephys@WikiRik do you think this could be re-opened? I believe it's still relevant and the stale bot closed it a while ago.
I have another use case for this, which adds to what OP requested. I'm using an association scope and through an unique key I know that there's one only row that will satisfy it through the junction table, but I'd like to receive a single item instead of an array.
// #1 scenario: a User has many Groups
models.User.belongsToMany(models.Group, {
foreignKey: 'userId',
through: UserGroups,
});
// #2 scenario: but a User only owns a single personal group
models.User.belongsToMany(models.Group, {
as: 'primaryGroup',
foreignKey: 'userId',
scope: {
groupType: 'personal'
},
through: {
model: UserGroups,
scope: {
isGroupOwner: true,
},
},
});
I know I could probably just set that the User owns the Group elsewhere, but it's desirable to have it centralized it in the junction UserGroup table, as it's subject to change.
The workaround provided by @simonbrent works, but it feels a bit hacky and I suppose this could change in future Sequelize versions since it seems to be overriding internal variables. (it actually did not work for me)
This could also potentially come as an option in belongsToMany like isSingleRow or whatever.
Activity
janmeier commentedon Jun 1, 2015
Through is only usefull for n:m which is handled by belongsToMany
verdier commentedon Jun 1, 2015
@janmeier, why no for N:1 such as in my previous exemple, I need this in a real world exemple:
janmeier commentedon Jun 1, 2015
If there is always only a single entry on one side of the relation, why do you need a join table?
Perhaps you can draw the relations, I can't really figure out your datamodel in my head :)
mickhansen commentedon Jun 1, 2015
Scratch my previous comment.
@verdier You are looking to fetch a relation via another relation? Rails support this i believe, we don't yet i'm afraid.
verdier commentedon Jun 1, 2015
@mickhansen yep, the query would be something like that:
No problem, I have solution for now.
verdier commentedon Jun 1, 2015
@janmeier the model is something like that:
A user have multiple operations, an operation have multiple breakdowns, but: a breakdown and an operation have only one same user. The
operationworks as a join table between onebreakdownand oneuser.I now that I can store the
userIdin thebreakdownAND in theoperationbut I will have to maintain theuserIdfields (ieoperation.userId === breakdown.userIdalways).mickhansen commentedon Jun 1, 2015
Or you can use a nested include.
verdier commentedon Jun 1, 2015
@mickhansen yep, but that's mean that if you fetch the user's breakdown, you'll fetch, for each breakdown, the operation. That's not very efficient. Something like:
would be very usefull.
note: that's not so good when you have a breakdown instance and you need the user. You have to fetch the operation.
mickhansen commentedon Jun 1, 2015
@verdier You'd need the join in any case.
verdier commentedon Jun 1, 2015
@mickhansen are you open for a pull request to support this feature:
note: I need a join, but without selecting any column of the
operationmodel.mickhansen commentedon Jun 1, 2015
@verdier You can disable attributes on the join with
include.attributes = [].Yes we'd be open to a pull request :)
The argument to
throughshould maybe be an Association rather than a Model, for less ambiguity, not sure.janmeier commentedon Jun 1, 2015
Not sure through is even a good name here - it might be too confusing..
mickhansen commentedon Jun 1, 2015
@janmeier Yeah i believe that's why Rails use through for this and pivot for our through.
verdier commentedon Oct 14, 2015
Here is a good article about
hasOne throughandbelongsTo throughusing ActiveRecord: http://www.rojotek.com/blog/2014/05/16/cool-stuff-you-can-do-with-rails-has_one/.1 remaining item
felixfbecker commentedon Jun 13, 2016
@mickhansen I just find the name
belongsToManyso confusing. The difference betweenhasManyandbelongsToManyis not clear at all.n:m in other languages:
has_and_belongs_to_many, that makes it more clear that it is basicallyhasMany, but both ways.@hasManyon both models withmappedByandinversedByparameters. The join table is set through@JoinTable.many-to-manycolumns on both models that both specify the same join table nametableI define my n:m relations in Sequelize in a similar way to the above:
Project.ts
User.ts
Usage
Basically I supply
throughas the join table name. And imo this would be nicer API if I could usehasManyfor this.mickhansen commentedon Jun 13, 2016
@felixfbecker We actually have
hasAndBelongsToManyas an alias forbelongsToMany.I understand your issue, but i don't think it's something we're likely to change right now, i prefer N:M being a seperate call from 1:M
felixfbecker commentedon Jun 13, 2016
@mickhansen did not know that, thanks! And I also think it's better to keep it, just wanted to share my thoughts.
overlookmotel commentedon Jun 13, 2016
If we think it's confusing, maybe make
hasAndBelongsToManythe main name listed in the docs withbelongsToManyas the alias, rather than the other way around?overlookmotel commentedon Jun 13, 2016
On the subject of
through, I feel thatthroughshould refer to the model name rather than the table name.Two reasons:
A small point perhaps, but I feel consistency is really important to get the "it just works" effect.
stale commentedon Jun 29, 2017
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂
heisian commentedon Apr 12, 2018
Have this issue as well. As a workaround my thoughts are:
@verdier OP's example:
Operationsa UNIQUE constraint on thebreakdown_idBreakdowncan only be associated once (toOperation), effectively giving theBreakdownonly one possible parent.Breakdown:@felixfbecker's example:
UserProjectsa UNIQUE constraint on theproject_idProjectcan only be associated once (toUser), effectively giving theBreakdownonly one possible parent.Project:And finally, for my glorious example:
A Referrer can have any number of Referral Programs that can have any number of Referrals.
A Referral can only belong to one Referral Program which can only belong to one Referrer.
A Referral can only belong to one Referrer through a Referral Program.
Referrrrrrrrrrrrrrrrrrr....
hassanhe commentedon Aug 27, 2018
@verdier OK this magically ✨ work's for me, @mickhansen @janmeier could any of you please explain why maybe it's already implemented there and useful I've seen a lot of requests for that feature.
even though the option
throughis not possible inbelongsToI've tried it and what makes it work that I've passed alsoforeignKey: 'id'which refers to theAFK in the join tableCif this has no unexpected behavior, the next step is how do we assign even more far nested joins like it
.ie
thank you ❤
zocoi commentedon Apr 24, 2019
@hassangit your example doesn't work for me, what do you do exactly?
odravison commentedon Sep 1, 2020
I passed by a lot of problem because Sequelize doesn't support this feature. Would be very nice to have this on this project!
It's very useful.
simonbrent commentedon Nov 10, 2020
I have noticed that if you do
then you get back the associated data as a single item rather than an array, while the SQL query does not change.
david-mart commentedon Jan 24, 2021
this actually works, thank you for a tip!
rdsedmundo commentedon Nov 8, 2023
@ephys @WikiRik do you think this could be re-opened? I believe it's still relevant and the stale bot closed it a while ago.
I have another use case for this, which adds to what OP requested. I'm using an association scope and through an unique key I know that there's one only row that will satisfy it through the junction table, but I'd like to receive a single item instead of an array.
I know I could probably just set that the User owns the Group elsewhere, but it's desirable to have it centralized it in the junction UserGroup table, as it's subject to change.
The workaround provided by @simonbrent works, but it feels a bit hacky and I suppose this could change in future Sequelize versions since it seems to be overriding internal variables.(it actually did not work for me)This could also potentially come as an option in
belongsToManylikeisSingleRowor whatever.