首页 > 语言 > PHP > 正文

thinkPHP5框架闭包函数与子查询传参用法示例

2024-05-05 00:04:48
字体:
来源:转载
供稿:网友

本文实例讲述了thinkPHP5框架闭包函数用法。分享给大家供大家参考,具体如下:

普通使用

举个栗子:

$this->where(function ($query){ $query->where('id', 1)->whereor('id', 2);})->find();

上述栗子就是一个简单的where查询的闭包函数使用,使用匿名函数添加复杂条件查询,

最后执行的sql是:

// 加入上述代码写在user模型里,则执行的sql为:select * from user where (id = 1 or id = 2);

复杂用法

其实闭包函数也不会复杂到哪去,无非带参数不带参数而已。举个栗子(上面的栗子加强下)

$this->where(function ($query) use ($id1, $id2){ $query->where('id', $id1)->whereor('id', $id2);})->find();

这也就是thinkphp 5 里怎么使用闭包查询传参数的方法,使用use 传入参数。

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程序设计有所帮助。


注:相关教程知识阅读请移步到PHP教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选