Optimizing activerecord queries

What is the basic principle in optimizing queries reg. activerecords? I’ve got orders which are related to orderdetails, products, rawmaterials etc. which are linked with the order-id. The more rows there are in the index-view, the slower it gets. Each row in index-view takes some millisecond since the relation is defined in the model class and when using the relation the SQL is executed (as you know). Any low hanging fruits in this case? Thanks.

  1. Make sure there are no repeating queries. If there are, check if with() should be added.

  2. If a single query is slow, get the execution plan with EXPLAIN, check what’s wrong and fix it.

Thanks. Here’s one example of eager loading that I now use:


$allorderdetails = Orderdetails::find()

	->with('order')

	->all();



The first orderdetail is found in index 0. Now I need sequential number to orders so I get one-to-one relation easily (?) How to add such number to SQL query (in ActiveDataProvider)? Might be hard to follow this text…need more info?

Yes. Haven’t got what you mean…