bookshelf: .through() does not work as expected
Here are my models:
// models/Org.js
var Org = bookshelf.Model.extend({
tableName: 'orgs',
admins: function () {
return this.hasMany('User').through('Admin')
}
})
module.exports = bookshelf.model('Org', Org)
// models/User.js
var User = bookshelf.Model.extend({
tableName: 'users',
org: function () {
return this.belongsTo('Org').through('Admin', 'id')
}
})
module.exports = bookshelf.model('User', User)
// models/Admin.js
var Admin = bookshelf.Model.extend({
tableName: 'admins'
})
module.exports = bookshelf.model('Admin', Admin)
The admins table referenced in the models/Admin.js model has a user_id column and an org_id column. When I invoke Org.forge({ id: 1 }).fetch({ withRelated: ['admins'] }), my expectation is that bookshelf will do the following:
- query the
adminstable to find all rows with a value of1in theorg_idfield - query the
userstable to find all users withids found in theuser_idcolumn of the rows found in theadminstable - return all of rows found in the
userstable when I perform `org.related(‘admins’).
This doesn’t seem to be the case, however; I get the following error message when I try the fetch statement above:
Error: select “users”.*, “admins”.“id” as “_pivot_id”, “admins”.“farm_id” as “_pivot_farm_id” from “users” inner join “admins” on “admins”.“id” = “users”.“admin_id” where “admins”.“farm_id” in (1) - SQLITE_ERROR: no such column: users.admin_id
This is puzzling; why would it try to find admin_id inside the users table to begin with? Then I tried making the following change to the Org model:
admins: function () {
return this.hasMany('User').through('Admin', 'id')
}
This does not result in a formal error, but the resulting admins array is incorrectly populated. It returns a user model whose id is the same as the org I am fetching instead of the user_id in the admins table. Simply put, my org’s id is 1, and its admin (as per the only row in the admins table) should be user with id 2, but the user that gets put into my org.admins array is the user with id 1.
Adding a third argument to the .through() method has no effect (as documented in issue #673) on the above results. Is this a bug, or am I doing something wrong?
Thanks!
About this issue
- Original URL
- State: open
- Created 9 years ago
- Comments: 27 (12 by maintainers)
Hey guys, firstly I’d like to apologise for the horrid wording on the
.through()docs - as I’m reading it even I am confused. Let’s leave this issue open to clean up the docs there.So, just to clarify the use of language here:
Now, the
throughForeignKeyis the column that is used to joinInterimtoThis.@agarzola, I’m going to show you the Model definitions one would use with the diagram you’ve provided.
Bookshelf doesn’t support models without a primary key, so
actor_film_mappingwouldn’t typically attract a Model. You can just usebelongsToMany.However, if you do want to create a join model using through, you should be able to do the following: