Usage Example of thinkPHP5 Framework Closure Function and Subquery Parameter Transfer

  • 2021-10-25 06:16:49
  • OfStack

This paper illustrates the usage of closure functions in thinkPHP5 framework. Share it for your reference, as follows:

General use

Take chestnuts:


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

The above chestnut is a simple one where Use of closure functions for queries, use anonymous functions to add complex conditional queries,

The last sql executed is:


//  Add the above code and write it in user Model, the executed sql Is: 
select * from user where (id = 1 or id = 2);

Complex usage

In fact, the closure function is not complicated, it is nothing more than taking parameters without parameters. Take a chestnut (the top chestnut is strengthened)


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

This is the thinkphp 5 how to use the closure query parameters, using use Pass in parameters.

Parameter transmission method of tp5 closed subquery

Query the fields status, channel_id, channel_name, account_level in the channel table, and the channel_id of these fields is not in the table adv_channel_rule where adv_id is $id:


$model = new Model();
$id = $req_models["id"];

tp5 Closed Subquery Reference:


$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();

Native writing of 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);

For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: