I’m trying to load all the contacts with the conversation, and it’s working unless I try to access the conversation attributes.
$contatos = Contato::whereBelongsTo($conta)->with('Conversa')->get();
foreach ($contatos as $contato) {
$saida_contato = new stdClass();
$saida_contato->nome_contato = $contato->nome;
$saida_contato->id = $contato->id;
$saida_contato->numero_contato = $contato->id_contato;
$saida_contato->conta_id = $contato->conta_id;
The code above executes two queries:
When I try to access the attributes of "conversa", it executes 90 queries.
$saida_contato->conversa_aberta = $contato->conversa->first()->id;
I can access the value that I want using:
contato->conversa[0]->aberta
, but when I do it, it generates a lot of queries.
Why is it executing the query for each contact if I have eager-loaded it before?
2
Answers
I had in my Contato Model:
so instead of getting the collection when using
$contato->conversa
, i was implicitly calling the method above causing to execute queries.Remove
first()
from$contato->conversa->first()->id
Since you’re using a
hasOne
relationship;$contato->conversa
will returns aModel
and not aCollection
.That’s the tricky part. If you’re using
first()
on a model, it will be the equivalent of doingConversa::first()
and will return the first model of your database through a new query.