幾種常見的where查詢:
1、關聯陣列查詢
$where = [ 'user_id'=>1, 'phone'=>'18311010011', 'is_delete'=>1 ]; $result = Db::name('user_card')->where($where)->select();
2、索引陣列查詢
$where = [ ['id','=', 253], ['is_delete','>=', 1], ['phone','like', '%186%'], ['sex','<>', '女'], ['create_time','between',['2020-05-12','2022-01-11']], ]; $result = Db::name('user_card')->where($where)->whereNotNull('birthday')->select();
null 和not null 不能放在where索引陣列總查詢,會變成比較字串。
解決方法:用鏈式函式 ->whereNotNull('birthday') 或者 whereNull(birthday)
$where = [ ['birthday','=','not null'] ]; $result = Db::name('user_card')->where($where)->select();
3、字串查詢:
Db::table('think_user')->whereRaw('type=1 AND status=1')->select();
4、多欄位相同條件查詢
Db::table('think_user') ->where('name|title','like','thinkphp%') ->where('create_time&update_time','>',0) ->find();
生成的SQL:
SELECT * FROM `think_user` WHERE ( `name` LIKE 'thinkphp%' OR `title` LIKE 'thinkphp%' ) AND ( `create_time` > 0 AND `update_time` > 0 ) LIMIT 1
5、適用場景查詢
a、where(C)->whereOR([A,B]) A和B是OR的關係,但是要和C是AND的關係
如果是這樣寫:
Db::table('think_user')->where(['is_delete' => 1])->whereOr($where)->select();
這樣寫,查詢出來的就是錯的,相當於只有第一個條件。
解決這個就需要用到閉包查詢:
Db::table('think_user') ->where(['is_delete' => 1]) ->where(function($query) use ($where){ $query->whereOr($where); }) ->select();
生成的SQL:
SELECT * FROM `un2co_user_card` WHERE `is_delete` = 1 AND ( `nickname` = '白小白' OR `phone` = '18606995547' )
還可以使用字串查詢:
Db::table('think_user') ->where(['is_delete' => 1]) ->whereRaw("nickname='白小白' OR phone='183144444444'") ->select();
打完收工!