サブクエリ順クエリ。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')
)

2つの列を比較するには、使用して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=373283&siteId=1