laravel - 加速 Eloquent 查询

标签 laravel performance eloquent

我正在尝试查询大量数据(40K 记录),并计划在未来查询更大的数据集。 Eloquent 似乎需要很长时间才能加载这些数据。我想知道是否有更快的方法来处理这些数据。我正在尝试查看我的数据的有效性,因此检查是否所有字段都为空。

我使用了常规的 Eloquent 调用。我不认为分 block 数据是合适的,因为我不打算以任何方式修改数据。我争论过是否经常运行一项工作并调用该工作的结果可能是一种更好的方法。

$journal = Journal::where('issn', $this->issn)->first();
$collection = $journal->outputs;
$collectionUnique = $collection->unique('doi');
$collectionDupes = $collection->diff($collectionUnique);

dd('Total Articles '.$this->getTotal(), 'Total Articles '.count($collection));

最佳答案

只需使用查询构建器!

为什么我们应该对大量记录使用查询构建器而不是 Eloquent ?!

原因如下:

Query Builder is so faster than Eloquent :

比较(Eloquent 与查询生成器):

To insert 1000 rows for a simple table Eloquent takes 1.2 seconds and in that case DB facades take only 800 mili seconds(ms).

另一个比较:

Eloquent ORM 平均响应时间

Joins | Average (ms) 
------+-------------
1     | 162,2 
3     | 1002,7 
4     | 1540,0 

Result of select operation average response time for Eloquent ORM

原始 SQL 平均响应时间

 Joins | Average (ms) 
------+-------------
1     | 116,4 
3     | 130,6 
4     | 155,2 

Result of select operation average response time for Raw SQL

For more information : Laravel Eloquent vs Query Builder


已编辑:

你的代码应该是:

$journal = DB::table('journals')->where('issn', $this->issn)->first();


然后用于使用集合(简单的方法):

$journal = Collection::make($journal); //For use Collection Methods
$collection = $journal->get("outputs");//Changed
$collectionUnique = $collection->unique('doi');
$collectionDupes = $collection->diff($collectionUnique);

dd('Total Articles '.$this->getTotal(), 'Total Articles '.count($collection));

最佳表现:

Use queries and Query Builder instead of collections . Because operations in SQL often is faster .

请比较你上一个代码和这个代码的时间,请在评论中告诉我:)

关于laravel - 加速 Eloquent 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56307841/

相关文章:

php - Ajax回拨和Laravel

c - C11中const限定符的性能优势

performance - 通过空矩阵乘法初始化数组的更快方法? (Matlab)

mysql - Laravel DB 查询给出了一组与直接 MySQL 查询不同的结果

laravel-5 - 在 Eloquent 中如何按列排序(如果存在)(否则使用另一列)?

php - 导入标题与数据库字段不同的 Excel 文档 - Laravel 5.2

php - 在 Laravel 中实现搜索 : Call to a member function posts() on null

laravel - 无法打开文件进行读取 [ 文件链接 ] laravel

Laravel 核心方法混淆

programming-languages - 什么时候计算或变量读取更快?