#BelongsToMany relationship slow eager loading query

5 messages · Page 1 of 1 (latest)

fallen flame
#

Hello, I'm running into performance issues with a belongsToMany relationship in Eloquent. The (simplified) database structure is as follows:

Table A:
id

Table B:
id_A
id_C

Table C:
id

Table A ~ 1k rows
Table B ~ 250k rows
Table C ~ 7k rows

Now i'm retrieving about 1000 C from a list of id's with eager loaded A's using the following query:

C::whereIn('id', $c_ids)->with('A')->get();

This query takes a crazy 10 seconds to complete. The querylog does not show any crazy queries (2 in total), with a time per query of about 500ms
Where are there 9 extra seconds coming from?

Running the query (->toSql()) directly in phpmyadmin (without LIMIT) runs in about 0.01 sec. There must be something going wrong.

#

The resulting MySql query is as follows (semi-pseudo):
select `A`.*, `B`.`C_id` as `pivot_C_id`, `B`.`A_id` as `pivot_A_id` from `A` inner join `B` on `A`.`id` = `B`.`A_id` where `B`.`C_id` in ([....])

elder frost
#

You're loading 1000 items, each of which have relations, so the amount of models would easily add up quite a bit. For each row that's received PHP objects need to be created (eloquent models), so that adds up in memory and cpu usage. You're comparing a plain query where the result is pretty much ignored versus hydrating all these models in a framework, so yeah, things are inherently going to be slower, especially if you're dealing with large datasets.

fallen flame
#

Is there any way to retrieve the related models as raw data objects with much less overhead?

#

Or a completely different approach?