Order query by subquery. Eloquent vs MySql

Deniss Muntjans :

I would like to get lists which are followed by a particular user and order lists by created_at(by date when lists were followed). Not sure why it doesn't work (order by) using Eloquent:

$myQuery = PlaceList::query()
   ->where('private', 0)
   ->whereHas('followers', function ($query) use ($userID) {
      $query->where('created_by_user_id', $userID);
   })
   ->orderByDesc(
      Follow::query()->select('created_at')
         ->where('created_by_user_id', $userID)
         ->where('followable_id', 'place_lists.id')
   )
   ->get()

This is what I've got when I use dd($myQuery->toSql()):

select 
    * 
from 
    `place_lists` 
where 
    `private` = ? 
    and exists (
                select 
                   * 
                from 
                   `follows` 
                where 
                   `place_lists`.`id` = `follows`.`followable_id` 
                   and `created_by_user_id` = ? 
                   and `follows`.`deleted_at` is null
                ) 
    and `place_lists`.`deleted_at` is null 
order by (
   select 
      `created_at` 
   from 
      `follows` 
   where 
      `created_by_user_id` = ? 
      and `followable_id` = ? 
      and `follows`.`deleted_at` is null
) desc

But when I populate MySql with data it does work:

select 
    * 
from 
    `place_lists` 
where 
    `private` = 0 
    and exists (
                select 
                   * 
                from 
                   `follows` 
                where 
                   `place_lists`.`id` = `follows`.`followable_id` 
                   and `created_by_user_id` = 13 
                   and `follows`.`deleted_at` is null
                ) 
    and `place_lists`.`deleted_at` is null 
order by (
    select 
        `created_at` 
    from 
        `follows` 
    where 
       `created_by_user_id` = 13 
       and `followable_id` = `place_lists`.`id`
       and `follows`.`deleted_at` is null
) desc

I'm well confused, what I'm doing wrong?

mrhn :

This query, you assert that followalbe_id is equal to 'place_lists.id'.

->orderByDesc(
    Follow::query()->select('created_at')
        ->where('created_by_user_id', $userID)
        ->where('followable_id', 'place_lists.id')
)

To compare two columns use whereColumn() instead.

->orderByDesc(
    Follow::query()->select('created_at')
        ->where('created_by_user_id', $userID)
        ->whereColumn('followable_id', 'place_lists.id')
)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=372177&siteId=1