如何通过关系循环获取所有用户

时间:2019-02-20 17:03:13

标签: php laravel

我有很多喜欢的人。每个喜欢都有一个属于->用户关系。         我如何获得所有用户。目前,我只吸引一位用户。

$likes = Like::where('thought_id', $thoughtComment->thought_id)->where('comment_id', $thoughtComment->id)->where('like_flag', 1)->get();


        foreach($likes as $like){
            $users = $like->user->username ?? '';
        }

        return $users;

1 个答案:

答案 0 :(得分:1)

好的。让我们从拥有的地方开始:

$likes = Like::where('thought_id', $thoughtComment->thought_id)->where('comment_id', $thoughtComment->id)->where('like_flag', 1)->get();
    foreach($likes as $like){
        $users = $like->user->username ?? '';
    }

    return $users;

接下来,让我们修复构建数组所需的操作,而不是继续覆盖相同的标量值。

$likes = Like::where('thought_id', $thoughtComment->thought_id)
    ->where('comment_id', $thoughtComment->id)
    ->where('like_flag', 1)->get();
$users = array(); //Users needs to be an empty array.

foreach($likes as $like){
    $users[] = $like->user->username ?? ''; // We append to it.
}

return $users;

但是我们可以做得更好,因为这将执行嵌套查询。因此,让我们使用with将用户加载到类似内容中,我们可以对其进行遍历。

$like = Like::where('thought_id', $thoughtComment->thought_id)
    ->where('comment_id', $thoughtComment->id)
    ->where('like_flag', 1)
    ->with([ // Eager the relationships we'll use
        'user' => function($query){
             $query->select('user.username'); 
             //But really, we only need the username
        }
    ])->get();

foreach($likes as $like){
    $users[] = $like->user->username ?? ''; // We append to it.
}

return $users;

然后使用集合的flatten和pluck函数,因此我们根本不必编写循环。

$like = Like::where('thought_id', $thoughtComment->thought_id)
    ->where('comment_id', $thoughtComment->id)
    ->where('like_flag', 1)
    ->with([
        'user' => function($query){
          $query->select('user.username');
        }
    ])->get();

//Lets get rid of the loop altogether and let the collection do the work.
$users = $like->flatten()->pluck('username');