mardi 24 juillet 2018

Order by column alias doesn't work with pagination in Laravel

I'm new to Laravel and I have this issue for which I can't find any solution anywhere.

I want to display a list of users and the number of devices they own (using a raw sub query). You can order by name or by number of devices and the number of items per page can change.

Here's my query to get data:

  $users = DB::table('Users as U')    
                ->select('U.Name', 'U.Firstname', 'U.Email'
                        DB::raw('(SELECT COUNT(*)
                            FROM Devices D
                            INNER JOIN Relation_Device_User RDU ON D.DeviceID = RDU.DeviceID
                            INNER JOIN Users US ON RDU.UsersID = U.UsersID
                            WHERE US.ADusername = U.ADusername) AS nb_devices'))
        ->orderBy($sort, $dir)->paginate($perpage);

Everything works fine. Sorting works. Pagination works. But if I sort by number of devices and then go to page 2 (or any page greater than 1), I got the following error:

SQLSTATE[42S22]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Nom de colonne non valide : 'nb_devices'. (SQL: select * from (select [U].[Firstname], [U].[Name], [U].[Email], (SELECT COUNT(*)
FROM Device D
INNER JOIN Relation_Device_User RDU ON D.DeviceID = RDU.DeviceID
INNER JOIN Users US ON RDU.UsersID = U.UsersID
WHERE US.ADusername = U.ADusername) AS nb_devices, row_number() over (order by [nb_devices] desc) as row_num from [Users] as [U]) as temp_table where row_num between 21 and 40)

There is no error on page 1, where sorting by number of devices works as expected. So I suspect the issue comes from the paginate function, but I have no idea how to solve this issue.

Any help would be appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire