Filter model based on a field from one of its relations
See original GitHub issueI must be missing something very basic, because it looks to me that this has to be a very common use case and I cannot figure out how to do it.
Let’s say I have a User and a Client models like this:
var User = bookshelf.Model.extend({
tableName: 'users',
client: function() {
return this.belongsTo(Client);
}
});
var Client = bookshelf.Model.extend({
tableName: 'clients',
users: function() {
return this.hasMany(User);
}
});
Client has a field called “is_active”. Now I want to get all users whose Client is active. Using raw knex I would do something as simple as this:
knex('users AS u') .join('clients AS c', 'c.id', 'u.client_id') .where({ 'c.is_active': true, }).then(function(users) {});
How would I do this using bookshelf? I only seem to find ways to filter the relation, but not to filter the model itself using fields from the relation.
Thanks.
Issue Analytics
- State:
- Created 8 years ago
- Comments:8 (4 by maintainers)
Top Results From Across the Web
django - Filtering one model based on another model's field
You filter with: postresult = Post.objects.filter( post_user__follow_target__follow_user=request.user ). The post_user will follow the ...
Read more >Aggregation | Django documentation
Here's how to do common aggregate queries, assuming the models above: ... Any filter() (or exclude() ) applied to normal model fields will...
Read more >Model relationships in Power BI Desktop - Microsoft Learn
A model relationship propagates filters applied on the column of one model table to a different model table. Filters will propagate so long...
Read more >Filter Data Across Multiple Data Sources - Tableau Help
Follow the steps below to learn how to filter data across multiple data sources. ... To edit an existing relationship, select the fields...
Read more >Getting Started — django-filter 22.1 documentation
Declaring filters¶ · field_name : The name of the model field to filter on. You can traverse “relationship paths” using Django's __ syntax...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
actually it would’ve been great to have some kind of query helper for this so you could do something like this:
or this:
Should be pretty straitforward since all the information is already there in
.relatedData
and there is no need for rewriting relation fetching itself.@helios1138 is correct. Currently relations do not know how to perform joins. You’ll have to manually add a join in the
query
callback.Something like this: