Filtering & Sorting by Model append Attributes #459
-
Is there any way to implement filtering & sorting by the model appended attributes ?
I want to do sorting on appended attributes such as average_rating , total_review_count, etc |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Appended attributes are added to the model after the database is queried. You will need to do a sort on the collection returned from the query.
|
Beta Was this translation helpful? Give feedback.
-
Hi! What @ashgibson says is true. The query builder builds Eloquent queries, it doesn't modify collections. Adding support for appended models might've been a mistake from the beginning 😅 I'd actually recommend looking into SQL and Eloquent queries more. Most of the extra attributes I add to models can actually be written as selects/joins/relations/etc. For your total review count example we actually support selecting and sorting by relationship count: $users = QueryBuilder::for(User::class)
->allowedIncludes([
'posts', // allows including `posts` or `postsCount`
])
->allowedSorts('posts_count'); Good luck! |
Beta Was this translation helpful? Give feedback.
Hi! What @ashgibson says is true. The query builder builds Eloquent queries, it doesn't modify collections. Adding support for appended models might've been a mistake from the beginning 😅
I'd actually recommend looking into SQL and Eloquent queries more. Most of the extra attributes I add to models can actually be written as selects/joins/relations/etc.
For your total review count example we actually support selecting and sorting by relationship count:
Good luck!