Sorting ignores relation condition
Hi,
I have been trying to get this to work but im stuck.
Basically i got a relation on my record called 'animals' and on the table i need to have several counts of this object with different conditions, like so:
Initially i had a custom attribute:
But i was unable to sort on this.
Then i figured maybe im able to push this logic to the database and add a virtual column with the count where active is true. But couldn't find any resource on how to do this.
So now i tried the sortable function but somehow when i sort it orders by the actual 'animals_count' (makes sense given the function). But this discards the "where animal is active".
Basically now im stuck and have not really an idea how to move forward... Anyone has experience with this of has some ideas?
7 Replies
@Augus van GIls So basically you trying to count active animals from the family model?
Hopefully that helps, here are the docs. - https://filamentphp.com/docs/3.x/tables/columns/relationships#counting-relationships @Augus van GIls 🙂
@CodeWithDennis that solution makes it that im unable to add multiple counts on the same table
You must name the column 'animals_count' but in FIlament you can't have two columns having the same name
This made me think, i am able to add another scoped relation in my model:
Model:
Table:
It's not really an elegant solution but so far it does work
You don't have to give them the same name i think. @Augus van GIls
Also, you don't have to add scopes. But its possible.
This one needs to have the 'animals_count' name
per documentation @CodeWithDennis
https://laravel.com/docs/11.x/eloquent-relationships#counting-related-models
Ah 😅
You got it working now?
Yea with a function withing my Model:
And this as a field:
Not sure if this is the proper way to go but it works
But this way i can have proper multiple count tables :