2016-12-07 10 views
0

私はLaravel 5.3パスポート(https://laravel.com/docs/5.3/passport)に基づいた小さなAPIに取り組んでいます。Laravel Eloquent 'with'は空の結果を返します

多くのグーグルで検索したところ、私の問題はまだ解明されていませんでした。 私はデータベースから従う人を検索する必要がある次の関数を持っています。これは素晴らしい作品です。その後、ユーザー情報、飲み物情報、ファイル情報、トースト情報でDBからすべての友人ステータスを取得する必要があります。これも素晴らしいです。ファイルやトーストやドリンクが空のときは機能しません。私は空の配列を返します。

機能:

public function index(Request $request) 
{ 
    $user = $request->user(); 

    $friends = Follow::with(['user'])->where('follows_user_id', '=', $user->id)->get(); 

    foreach ($friends as $friend) { 

     $status = Status::with(['user', 'drink', 'file', 'toast'])->where(
      'user_id', '=', $friend->id 
     )->CreatedAtDescending()->get(); 

    } 

    if (!isset($status) || empty($status)) { 
     return response(['message' => 'Nothing found.'], 404); 
    } 

    return $status; 
} 

は、どのように私はドリンクやファイルやトーストが空の場合でも、戻って結果を得ることができますか?

答えて

0

私はそれを動作させました!解決策は次のとおりです。

public function index(Request $request) 
{ 
    $user = $request->user(); 

    $friends = Follow::with(['user'])->where('follows_user_id', '=', $user->id)->get(); 

    foreach ($friends as $friend) { 

     $status = Status::with(['user' => function ($query) use ($friend) { 
      $query->where('id', '=', $friend->following_user_id); 
     }, 'drink', 'file', 'toast'])->get(); 
    } 

    if (!isset($status) || empty($status)) { 
     return response(['message' => 'Nothing found.'], 404); 
    } 

    return $status; 
} 

ここでは、クエリでわずかな問題があります。

関連する問題