Laravel 5雄辩的大块数据

时间:2016-02-15 21:17:52

标签: laravel laravel-5 eloquent query-optimization

我在表中有更多50000条记录。关系很多很多。

记录模型:

 public function busines(){
        return $this->belongsToMany('App\Busines', 'busines_record', 'record_id', 'busines_id');
    }

商业模式:

 public function records()
    {
        return $this->belongsToMany('App\Record', 'record_id');
    }

我的查询:

 $data = Records::with('busines')->where('show', '=', 1)->get();

查询是长执行。如何优化查询?

1 个答案:

答案 0 :(得分:0)

你可以对它进行分页:

$records = Records::with('busines')->where('show', '=', 1)->paginate();

并在视图中显示分页:

{!! $records->links() !!}

或者你可以使用chunk(参见query builder docs“从表中分块结果”):

Records::with('busines')->chunk(100, function($records) {
    foreach ($records as $record) {
        dump($record->id);
    }
});