skip to Main Content

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:
result of contacts

When I try to access the attributes of "conversa", it executes 90 queries.

 $saida_contato->conversa_aberta = $contato->conversa->first()->id;

enter image description here

I can access the value that I want using:
contato->conversa[0]->aberta, but when I do it, it generates a lot of queries.

data

Why is it executing the query for each contact if I have eager-loaded it before?

2

Answers


  1. Chosen as BEST ANSWER

    I had in my Contato Model:

     public function getconversaAttribute()
    {
    
        return $this->conversa()->get();
    
    }
    

    so instead of getting the collection when using $contato->conversa , i was implicitly calling the method above causing to execute queries.


  2. Remove first() from $contato->conversa->first()->id

    Since you’re using a hasOne relationship; $contato->conversa will returns a Model and not a Collection.

    That’s the tricky part. If you’re using first() on a model, it will be the equivalent of doing Conversa::first() and will return the first model of your database through a new query.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search