laravel-rest-api icon indicating copy to clipboard operation
laravel-rest-api copied to clipboard

Impossible to sort on relation field

Open Samoht70 opened this issue 2 years ago • 2 comments

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

Samoht70 avatar Feb 14 '24 08:02 Samoht70

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

GautierDele avatar Feb 20 '24 17:02 GautierDele

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:
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

sneakylenny avatar Apr 08 '24 13:04 sneakylenny