简体   繁体   English

使用多个 withCount() 检索集合加载时间太长 (Laravel)

[英]Retrieve collection with multiple withCount() takes too long to load (Laravel)

I'm working on a query that the model needs to count some data with different conditions from its related tables.我正在处理 model 需要从其相关表中计算一些具有不同条件的数据的查询。 Currently I'm using multiple withCount() with different condition to get the desire outcome.目前,我正在使用具有不同条件的多个 withCount() 来获得所需的结果。

When I paginate the query is fine, but one of my requirement is to retrieve all rows and process them in one go. When I retrieve all, the performance is very slow.当我对查询进行分页时很好,但我的要求之一是检索所有行并在一个 go 中处理它们。当我检索所有行时,性能非常慢。 The total record is only 2000 rows.总记录只有 2000 行。

$products = Product::withCount(['tableA AS tableA_condition_A' => function($query){
   $query->whereIn('status', [1,2,3])->whereNotIn('type', [1,2,3]);
}])
->withCount(['tableA AS tableA_condition_B' => function($query){
   $query->whereIn('status', [1,2,3])->whereIn('type', [1,2,3]);
}])
->withCount(['tableB AS tableA_condition_A' => function($query){
   $query->whereNotIn('type', [1,2,3])->whereHas('tableC.tableD', function($subquery){
        $subquery->whereIn('group', [1,2,3])->whereIn('state', [1,2,3]);
   });
}])
->withCount(['tableB AS tableA_condition_A' => function($query){
   $query->whereIn('type', [1,2,3])->whereHas('tableC.tableD', function($subquery){
        $subquery->whereIn('group', [1,2,3])->whereIn('state', [1,2,3]);
   });
}])
// has a few more similar withCount() with condition
->get();

// before go into foreach, the get will take a long time

// after retrieve products withCounts data, process
foreach($models as $model){
   // process...
}

I've tried several ways to optimize my query but this gives the best performance of all.我已经尝试了几种方法来优化我的查询,但这是所有方法中性能最好的。

I know each row are executing queries that's why its performance is slow.我知道每一行都在执行查询,这就是它的性能很慢的原因。 Is there any way or good practice on improve the performance on this?有什么方法或好的做法可以提高这方面的表现吗? The code above is just an example.上面的代码只是一个例子。 Thank you in advance!先感谢您!

My first way is I tried to use foreach() to calculate each row's related tables, but this has the worst performance of all.我的第一种方法是尝试使用 foreach() 来计算每一行的相关表,但这是所有方法中性能最差的。

Second way is to use with() eager loading from its related tables and do collection filtering, but is performance doesn't improve.第二种方法是使用 with() 从其相关表中预加载并进行集合过滤,但性能没有提高。

The third way is the above code, that has the best performance of all.第三种方法是上面的代码,它具有最好的性能。

I have indexed all of my tables, so indexing should not be a problem.我已经为我的所有表编制了索引,因此编制索引应该不是问题。

You try using "Index" the columns in each table that are linked together, it will optimize the query for you.您尝试使用“索引”链接在一起的每个表中的列,它会为您优化查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM