Lomkit / laravel-rest-api

Generate Api in seconds
https://laravel-rest-api.lomkit.com/
MIT License
444 stars 25 forks source link

Impossible to sort on relation field #104

Open Samoht70 opened 7 months ago

Samoht70 commented 7 months ago

Laravel Rest Api Version

2.5.1

Laravel Version

10.43.0

PHP Version

8.1

Database Driver & Version

No response

Description

I wanted to sort my users according to their role (I use laravel-spatie permission). I'm getting an error telling me that my field is invalid. Capture d'écran 2024-02-14 095119

Here's the body of my request: { "search": { "sorts": [ {"field": "roles.id", "direction": "desc"} ] } }

After looking a little in the code I saw that it came from the SearchRules.php file. It's based on the fields in the current UserResource for me.

Do you think this will be implemented in the future?

Steps To Reproduce

ddzazda

GautierDele commented 7 months ago

This is laravel native feature, will need to see if it's on the route or no. Meanwhile I'll let it open

timyourivh commented 5 months ago

Same goes for trying to sort by aggregated data. For example: Sort by posts by most comments. comments_count is not available as field.

More Adding the aggregated field to the `fields()` method in your resource won't work either because when the sorts are applied, it prefixes the table to the field and it will throw: "Column not found: 1054 Unknown column 'posts.comments_count' in 'order clause'" because the table name is not prefixed to the aggregated select: ```sql select `posts`.*, ( select count(*) from `comments` where `posts`.`id` = `comments`.`post_id` limit 50 ) as `comments_count` # won't match the "order by `posts`.`comments_count`" instruction from `posts` order by `posts`.`comments_count` # won't work with the `comments_count` aggregation desc limit 50 offset 0 ```