E
E
Ernest Faizullin2018-11-12 13:20:31
Laravel
Ernest Faizullin, 2018-11-12 13:20:31

Optimizing a database query with a selection of rows that contain relationships?

Hi all. There is a controller to fetch all records of the Survey model, and each Survey has a Respondents relationship. The controller finds all Surveys and passes them to the transformer (SurveyTransformer), where each Survey is added with the respondents_count field, the number of respondents in the ManyToMany relationship. But it turns out to be very expensive: for each Survey, access the database to find out the number of respondents belonging to it.
How can this moment be optimized? Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin B., 2018-11-12
@erniesto77

To do this, there are methods with, load
If only the number is needed, then withCount

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question