Laravel Eloquent Inner Join查询动态多条件在Where子句

时间:2018-01-30 09:59:04

标签: mysql laravel-5.4

在下面的Eloquent Query示例中,正如我们所看到的,我正在尝试在where子句中添加条件,只有在$ request数据中接收到它的值时。 如果在用于检查isset的Eloquent查询之间,我会收到写入错误。有没有办法只在设置条件时动态添加条件?

 SampleMaster::from('sample_master as sm')          
        ->join('example_master as em', 'sm.e_id', '=', 'em.id')
        ->select(['sm.col1','sm.col2','em.col3'])     
        if(isset($request->sample_id))
        {
           ->where('sm.sample_id',$request->sample_id) 
        }
        if(isset($request->example_id))
        {
            ->where('sm.example_id',$request->example_id) 
        }
        if(isset($request->f_id))
        {
            ->where('sm.f_id',$request->f_id) 
        }
        if(isset($request->g_id))
        {
            ->where('sm.g_id',$request->g_id) 
        }            
        ->groupby(['sm.col1','sm.col2','em.col3'])
        ->get()->all();

另外,我想概括一下Eloquent Query,如果没有传递任何参数,那么应该有一些默认值,如我们在phpmyadmin中看到的那样

SELECT * FROM `sample_master` WHERE 1

这样我可以直接继续在$ where_array中附加key =>值(如果存在),以防我不使用连接。

0 个答案:

没有答案