如何在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);

关于如何在thinkPHP5框架中使用闭包函数问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。