如何在 laravel 5.4 中向 DB::table 添加多个作用域

how to add multiple scope to DB::table in laravel 5.4

我是 laravel 5 的新手,我试图像这样添加多个范围:

$projects = DB::table('projects AS p')->select('p.project_name','c.name_country', 'p.date_project','s.name_status','p.rejected_date')                    
                    ->join('country AS c','c.id','=','p.id_country')
                    ->join('status AS s','s.id','=','p.id_status')
                    ->where('p.active','=','1');  

$projects = $this->scopeCountry($projects , $country);
$projects = $this->scopeStatus($projects , $status);  
$projects->get(); 
return view('search.ajax')->with('projects', $projects);
}
    public function scopeCountry($query, $country){
            return is_null($country) ? $query : $query->where('p.id_country','=',$country);
        }

public function scopeStatus($query, $status){
            return is_null($status) ? $query : $query->where('p.id_status','=',$status);
        }
}

它给了我这个错误: 26864233b0cd26a1055b66c2645628be451523fd.php 第 4 行中的错误异常:未定义 属性:Illuminate\Database\MySqlConnection::$project_name(视图:/home/vagrant/Code/projects/resources/views/search/ajax.blade.php)

我注意到如果我这样修改它就不会出现这个错误:

//$projects = $this->scopeStatus($status);  
//$projects->get(); 

然后我在以下位置添加 get() 函数:

public function scopeCountry($query, $country){
                return is_null($country) ? $query->get() : $query->where('p.id_country','=',$country)->get();
            }

我不在一个范围内添加查询并使用 is_null($country) 的原因是,万一那些变量 ($country, $status) 为 null 只有主查询应该执行:

$projects = DB::table('projects AS p')->select('p.project_name','c.name_country', 'p.date_project','s.name_status','p.rejected_date')                    
                        ->join('country AS c','c.id','=','p.id_country')
                        ->join('status AS s','s.id','=','p.id_status')
                        ->where('p.active','=','1'); 

而且我还必须将类似的范围添加到另一个字段,也许还有另一种方法可以做到,我不确定。谢谢。

我刚刚使用 when 方法找到了一个更简单的解决方案:

$projects = DB::table('projects AS p')->select('p.project_name','c.name_country', 'p.date_project','s.name_status','p.rejected_date')                    
                        ->join('country AS c','c.id','=','p.id_country')
                        ->join('status AS s','s.id','=','p.id_status')
                        ->where('p.active','=','1') 
                        ->when($country, function($query) use ($country){
                             return $query->where('p.id_country','=',$country);
                        })
                        ->when($status, function($query) use ($status){
                             return $query->where('p.id_status','=',$status);
                        }); 

当 $country 或 $status 变量不存在或为空时,闭包中的内容不会执行。