Laravel Eloquent 仅在需要时使用 where 和 order 条件

德林格林

请看下面的代码。这段代码是我用 Codeigniter 编写的。我需要强调的是,只有在设置了这些发布请求的情况下,条件和订单条件才起作用。否则我只是select * from student

Codeigniter 代码

$this->db->select('*');
$this->db->from('student');
if($this->input->post('first_name') != NULL){
    $first_name = $this->input->post('first_name');
    $this->db->where('first_name', $first_name);
}

if($this->input->post('last_name') != NULL){
    $last_name= $this->input->post('last_name');
    $this->db->where('last_name', $last_name);
}

if($this->input->post('order_by') != NULL){
    $order_by= $this->input->post('order_by');
    $this->db->order_by($order_by);
}

$query = $this->db->get();

Laravel 代码

我将用 laravel 做同样的事情。

$first_name = $request->input('first_name');
$last_name = $request->input('last_name');
$order_by = $request->input('$order_by');

$students = Student::orderBy($order_by)
      ->where('first_name',$first_name)
      ->where('last_name',$last_name);
      ->paginate(10);

我能够运行上面的代码。该代码在所有发布请求都存在时起作用。

但如果没有first_name发布请求,我需要删除->where('first_name',$first_name).

如果我没有order_by发布请求,我需要删除orderBy($order_by).

如何使用上面的 Laravel 代码做到这一点。

纳文

你可以使用像,

$students = Student::latest();

if (isset($request->input('order_by'))) {
    $students->orderBy($order_by)
}
if (isset($request->input('first_name'))) {
          $students->where('first_name',$first_name);
}
if (isset($request->input('last_name'))) {
          $students->where('last_name',$last_name);
}
$students->paginate(10);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Laravel 4:使用Eloquent的where中的where和whereIn

如何在Laravel Eloquent中使用多个where条件?

如何在 Laravel Eloquent 中使用 GroupBy 和 Where 子句?

如何在 Laravel 5.8 上使用 where 和 groupBy eloquent

Laravel在使用where条件和更新时提供不同的结果

Laravel 使用无条件查找和动态 where 条件

Laravel Eloquent-仅在“ with”中的“ where”条件为true的情况下获取关系元素

Laravel Eloquent 如何为数据透视表选择使用条件“where”

在laravel中使用“AND”和“OR”运算符的多个where条件

多个 where 条件对 Laravel eloquent 不起作用

使用Laravel Eloquent创建嵌套OR条件

Laravel Eloquent在联接中使用WHERE代替AND

Laravel Eloquent - 使用关系构建“where not”查询

使用 where 和关系查找 Eloquent 模型

Laravel Eloquent 查询带有 where 和 wherehas 关系表

Laravel - Eloquent where with array

Laravel Eloquent Where With

Laravel eloquent:接收多个ID时如何使用“where”?

使用Laravel Eloquent的with()函数和内部联接

Laravel Eloquent Where、orWhere 和 Find 在同一个 eloquent 查询中的问题

Eloquent 查询不使用 where/first 条件。为什么?

关系满足Laravel Eloquent条件时如何获取产品

使用Laravel和两个WHERE条件查询两个表

Laravel Eloquent Multiple Where with count

Laravel 5 Eloquent AND 而不是 where

Laravel 5.8:Eloquent where 子句返回 null 但不执行 if..empty 条件

SQL内部连接使用where和order by

如何在 Laravel Eloquent 模型中使用 where

使用Eloquent Where逃离Laravel DB:raw查询