Laravel 5雄辩的条件链查询

时间:2016-03-11 02:39:32

标签: laravel laravel-5 eloquent

需要关于这个简单代码的帮助,我应该替换哪些代码 $users = User::all();所以我可以有条件地链接范围方法并在最后对它进行分页?

我尝试使用User启动$users = new User();对象并且出现错误,在VIEW使用时尝试获取非对象错误的属性。

public function index()
{
    // user search

    $name = $this->request->name;
    $email = $this->request->email;

    $users = User::all();

    if (!empty($name)) {
        $users->name($name);
    }

    if (!empty($email)) {
        $users->email($email);
    }

    $users->paginate(5);

    return view('admin.users.index',compact('users'));
}

提前致谢

3 个答案:

答案 0 :(得分:1)

试试这个:

$users = new User;
if( !empty($name) )
   $users->whereName($name);
if( !empty($email) )
   $users->whereEmail($email);
$users =$users->paginate(5);

答案 1 :(得分:1)

$users = DB::table('users');

$users = empty($email) ? $users->paginate(5) : $users->whereEmail($email)->paginate(5);

如果所有用户都有电子邮件,则无需检查姓名,因为电子邮件始终是唯一的。这种方式可以更快,更方便地完成任务。

如果您需要检查name或其他任何内容,可以使用以下命令:

$users = DB::table('users');

$users = empty($email) ? $users : $users->whereEmail($email);
$users = empty($name) ? $users : $users->whereName($name);

$users = $users->paginate(5);

答案 2 :(得分:0)

我从以下链接中找到答案

https://stackoverflow.com/a/21739314/417899

例如代码:

$users = new User;

if (!empty($name)) {
    $users = $users->name($name);
}

$users = $users ->paginate(5);