하위 쿼리에 의해 주문 쿼리. MySQL의 대 웅변

데니스 Muntjans :

나는에 의해 특정 사용자 및 주문리스트가옵니다 목록을 좀하고 싶습니다 created_at(목록은 다음 때 날짜). 확실하지 왜 설득력을 사용 (순서) 작동하지 않습니다

$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()

이것은 내가 사용할 때 내가있어 무엇 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

내가 데이터를 MySQL의를 채울 때이 작업을 수행합니다 :

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

나는 물론 내가 잘못을 뭘하는지 혼란있어?

mrhn :

이 쿼리는, 당신은 그 주장 followalbe_id과 동일하다 'place_lists.id'.

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

두 개의 열이 사용 비교하려면 whereColumn()대신.

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

추천

출처http://43.154.161.224:23101/article/api/json?id=373280&siteId=1