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

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《Zend FrameWork框架入门教程》及《PHP模板技术总结》。

希望本文所述对大家基于ThinkPHP框架的PHP程序设计有所帮助。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容