zfxcms ^回到顶部

您的当前位置:首页 > php资讯 > Laravel框架 > laravel的条件查询where的且、或关系总结

laravel的条件查询where的且、或关系总结

所属分类: Laravel框架   2018-07-24 10:30:04  编辑:admin  浏览次数 1188 次

且的关系
$where = array();
if (!empty($input['字段'])) {
    $where[] = ['a.字段','=',$input['字段']];
}
if (!empty($input['字段'])) {
    $where[] = ['a.字段','like','%'.$input['字段'].'%'];
}
if (!empty($input['字段'])) {
    $where[] = ['a.字段','like','%'.$input['字段'].'%'];
}
//下面直接用where($where)
或的关系
if (!empty($input['keywords'])) {
    $where = [
        ['a.字段1','like','%'.$input['keywords'].'%'],
        ['a.字段3','=',$input['id']]
    ];
    $where1 = [
        ['a.字段2','like','%'.$input['keywords'].'%'],
        ['a.字段3','=',$input['id']]
    ];
}else{
    $where = [
        ['a.字段3','=',$input['id']]
    ];
    $where1 = [
        ['a.字段3','=',$input['id']]
    ];
}
$userNum = DB::table('表1 as a')
    ->where($where)
    ->orwhere($where1)
    ->select('a.id')->count();
且、或、原生
$inforList = DB::table('表1 as a')
    ->leftJoin('表2 as b', function ($join) {
        $join->on('a.issuetype', '=', 'b.code')->where('b.type', '=', 'issuetype');
    })
    ->leftJoin('表3 as c','a.operator', '=', 'c.id')
    //这个$where是动态条件
    ->where($where)
    //这个where是固定条件
    ->where([
            ['a.istatus','=',1],
            ['a.igrade','>=',$grade_id]
    ])
    //$whereRaw原生输入
    ->whereRaw("position(',$uid,' in a.uid) >0")
    //$orwhere是或的关系
    ->orwhere('a.operator','=',$uid)
    ->select('a.id','a.title','b.name','a.inforunit','c.username','a.issuetime','a.browsenum')
    ->orderBy('a.issuetime')
    //分页
    ->limit($pageSize)
    ->offset($pageIndex)
    ->get();
与或一起查
->where('a.aid',$input['id'])
->where('a.isdel','1')
->where(function($query){
    $query->where('userjob','=','1')
        ->orWhere(function($query){
            $query->where('userjob', '2');
        })
        ->orWhere(function($query){
            $query->where('userjob', '3');
        });
})
原来的sql是and isdel=1 and (userjob=1 or userjob=2 or userjob=3)";

$where = [];
$orwhere = [];
//如果查询条件的话
if (!empty($input['keywords'])) {
    $keywords_all = trim(strtr($input['keywords'], array('+'=>'',' '=>''
    ,'-'=>'','_'=>'',','=>'')));
    //如果是列表查询的话,
        $where []=[function($query) use($input['keywords']) {
               $query -> where()
               ->orwhere()
        }];
}
if (!empty($input['userjob'])) {
    $where[] = ['a.userjob','=',$input['userjob']];
}
if($uid == 1){
    $data = DB::table('表名称')
        ->where($where)
        ->get();
 子查询-嵌套查询
DB::table('users')
    ->whereExists(function ($query) {
    $query->select(DB::raw(1))
    ->from('orders')
    ->whereRaw('orders.user_id = users.id');
        })
    ->get();
上述的查询将生成以下 SQL:

select * from users
where exists (select 1 from orders where orders.user_id = users.id)

PHP文章检索

PHP文章目录