Eloquent where子句有多个condtion过滤器

时间:2015-12-31 10:15:31

标签: php laravel laravel-5.1

在我的数据库表中,我有一个名为student add的表,我希望获取具有以下所有条件的特定学生,这些条件存储在filters数组中,并带有其他选项(“like name可以是middlename或lastname”)

$filters = [
                ['type' => 'name', 'value' => 'Abhishek'],
                ['type' => 'roll', 'value' => '0013']
            ];
  

我正在尝试使用以下代码

获取该数据
 $student = Student::where(function ($query) use ($filters) {

            foreach($filters as $filter) {
                switch($filter['type']){
                    case 'name' :
                        $query->where('firstname', $filter['value'])
                        ->orWhere('middlename', $filter['value'])
                        ->orWhere('lastname', $filter['value']);
                        break;
                    case 'roll' :
                        $query->where('rollnumber', $filter['value']);
                        break;

                }
            }
        })
        ->get();
  

我在这里使用advance where子句但它运行的第一个参数(如名称)只表示我得到的值其中name = filters ['value'] 为什么它如此

2 个答案:

答案 0 :(得分:0)

为什么在查询中使用案例?只需用多个where子句写2,然后用if语句选择它:)

答案 1 :(得分:0)

对于这个SQL

select * from `students` where ((`firstname` = ? or `middlename` = ? or `lastname` = ?) and `rollnumber` = ?)

    $student = Student::where(function ($query) use ($filters) {

        foreach($filters as $filter) {
            switch($filter['type']){
                case 'name' :
                    $query->where(function ($query) use ($filter) {
                        $query->where('firstname', $filter['value'])
                            ->orWhere('middlename', $filter['value'])
                            ->orWhere('lastname', $filter['value']);
                    });//This will add a parenthesis for all wheres
                    break;
                case 'roll' :
                    $query->where('rollnumber', $filter['value']);
                    break;

            }
        }
    })
        ->get();//Replace get with toSql to see SQL

对于这个SQL

select * from `students` where ((`firstname` = ? or `middlename` = ? or `lastname` = ?) or `rollnumber` = ?)

    $student = Student::where(function ($query) use ($filters) {

        foreach($filters as $filter) {
            switch($filter['type']){
                case 'name' :
                    $query->orWhere(function ($query) use ($filter) {//add or where for or where
                        $query->where('firstname', $filter['value'])
                            ->orWhere('middlename', $filter['value'])
                            ->orWhere('lastname', $filter['value']);
                    });//This will add a parenthesis for all wheres
                    break;
                case 'roll' :
                    $query->orWhere('rollnumber', $filter['value']);//add or where for or where
                    break;

            }
        }
    })
        ->get();//Replace get with toSql to see SQL