laravel cursor的底层实现

发布时间:2020-03-18 12:35:34 作者:hgditren
来源:网络 阅读:2750
foreach (BillInfo::where('id', '>', 0)->orderBy('id', 'desc')->limit(10000)->cursor() as $value) {
   print_r($value);
}


Illuminate\Database\Query\Builder.php;
/**
* Get a generator for the given query.
*
* @return \Generator
*/
public function cursor()
{
   if (is_null($this->columns)) {
       $this->columns = ['*'];
   }

   return $this->connection->cursor(
       $this->toSql(), $this->getBindings(), ! $this->useWritePdo
   );
}


Illuminate\Database\Connection.php;
/**
* Run a select statement against the database and returns a generator.
*
* @param  string  $query
* @param  array  $bindings
* @param  bool  $useReadPdo
* @return \Generator
*/
public function cursor($query, $bindings = [], $useReadPdo = true)
{
   $statement = $this->run($query, $bindings, function ($query, $bindings) use ($useReadPdo) {
       if ($this->pretending()) {
           return [];
       }

       // First we will create a statement for the query. Then, we will set the fetch
       // mode and prepare the bindings for the query. Once that's done we will be
       // ready to execute the query against the database and return the cursor.
       $statement = $this->prepared($this->getPdoForSelect($useReadPdo)
                         ->prepare($query));

       $this->bindValues(
           $statement, $this->prepareBindings($bindings)
       );

       // Next, we'll execute the query against the database and return the statement
       // so we can return the cursor. The cursor will use a PHP generator to give
       // back one row at a time without using a bunch of memory to render them.
       $statement->execute();

       return $statement;
   });

   while ($record = $statement->fetch()) {
       yield $record;
   }
}
推荐阅读:
  1. Laravel - php artisan 研究
  2. 使用Lazy Collections来提高 Laravel Excel读取性能的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

laravel yield 生成器

上一篇:在团800运维工作总结之couchbase使用

下一篇:perl学习之nagios脚本

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》