1

我有一个 foreach 循环,每次匹配某个值,然后获取相关记录

 foreach($results as $result){
    // Value may be 1,2,3 etc
    if($result->id == $value){
       $users = User::whereId($value)->get();
    }
  }
  return view('index',compact('users'));

现在如何将所有用户记录传递给视图?目前它只获取第一条记录!

4

3 回答 3

1

您可以将所有 id 存储在一个数组中,然后一次获取所有记录。在循环中运行数据库查询会产生性能开销

$userIds = [];

foreach ($results as $result) {
    // Value may be 1, 2, 3 etc.
    if ($result->id == $value){
        $userIds[] = $value;
    }
}

$users = User::whereIn('id', $userIds)->get();

return view('index', compact('users'));
于 2017-07-30T20:45:44.410 回答
0

So what you want to do is:

  • Make a new array that holds arrays of users when it matches
  • Then return that new array

Example:

$matchedUsers = array();

foreach($results as $result) {
    // Value may be 1,2,3 etc
    if($result->id == $value) {
       $matchedUsers[] = User::whereId($value)->get();
    }
}
return view('index', compact('matchedUsers'));

An even cleaner way to do this is to have a seperate function that does your call for User Info when it matches:

public function getUsers($results)
{
    $matchedUsers = array();

    foreach($results as $result){
        // Value may be 1,2,3 etc
        if($result->id == $value) {
            $matchedUsers[] = User::whereId($value)->get();
        }
    }
    return view('index', compact('matchedUsers'));
}

public function getMatchedUser($userId)
{
    return User::whereId($userId)->get();
}
于 2017-08-01T05:06:29.627 回答
0

为此,您可以使用“whereIn”。

您可以从 Laravel 文档中获取更多信息

$ids = [];

foreach ($results as $result) {

    if ($result->id == $value){
        $ids[] = $value;
    }
}

$users = User::whereIn('id', $ids)->get();

return view('index', compact('users'));
于 2017-08-04T06:22:13.413 回答