本文實例講述了thinkPHP5框架閉包函數(shù)用法。分享給大家供大家參考,具體如下:
普通使用
舉個栗子:
$this->where(function ($query) { $query->where('id', 1)->whereor('id', 2); })->find();
上述栗子就是一個簡單的where
查詢的閉包函數(shù)使用,使用匿名函數(shù)添加復(fù)雜條件查詢,
最后執(zhí)行的sql是:
// 加入上述代碼寫在user模型里,則執(zhí)行的sql為: select * from user where (id = 1 or id = 2);
復(fù)雜用法
其實閉包函數(shù)也不會復(fù)雜到哪去,無非帶參數(shù)不帶參數(shù)而已。舉個栗子(上面的栗子加強下)
$this->where(function ($query) use ($id1, $id2) { $query->where('id', $id1)->whereor('id', $id2); })->find();
這也就是thinkphp 5 里怎么使用閉包查詢傳參數(shù)的方法,使用use
傳入?yún)?shù)。
tp5閉包子查詢傳參方法
在channel表中查詢status,channel_id,channel_name,account_level這些字段,且這些字段的channel_id不在adv_id為$id的表adv_channel_rule中:
$model = new Model(); $id = $req_models["id"];
tp5閉包子查詢傳參:
$res = $model->table('channel') ->field(['status','channel_id','channel_name','account_level']) ->where('channel_id','NOT IN',function($query) use ($id) { $query->table('adv_channel_rule')->where("adv_id",$id)->field('channel_id'); })->select();
mysql的原生寫法:
$res = 'SELECT adv_id,adv_name,status,account_level FROM `channel` WHERE channel_id NOT IN (SELECT channel_id FROM adv_channel_rule WHERE adv_id='.$id.')'; $result = $model->query($res);
希望本文所述對大家基于ThinkPHP框架的PHP程序設(shè)計有所幫助。