Php 如何通过循环中的关系获取所有用户
我收集了很多喜欢的东西。每个like都有一个属于->用户关系。 如何获取所有用户。目前我只得到一个用户Php 如何通过循环中的关系获取所有用户,php,laravel,Php,Laravel,我收集了很多喜欢的东西。每个like都有一个属于->用户关系。 如何获取所有用户。目前我只得到一个用户 $likes = Like::where('thought_id', $thoughtComment->thought_id)->where('comment_id', $thoughtComment->id)->where('like_flag', 1)->get(); foreach($likes as $like){
$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();
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;
但我们可以做得更好,因为这将执行嵌套查询。因此,让我们用和将用户加载到like中,我们可以循环使用它
$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;
然后使用集合的展平和拾取功能,这样我们就不必编写循环
$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');
$users[]=$like->user->username??”代码>-不要忘记在循环之前初始化数组。你也可以省略没有用户名的用户,但这取决于你自己。谢谢。我也不会忘记急切地加载这个关系来解决这个循环的n+1问题<代码>类似::with('user')->其中('think_id…)