How to ignore the default Model $with in Laravel (Eloquent ORM)

Asked

Viewed 46 times

1

I have a model with with already predefined calling some other models.

public $with = ["itens", "filial", "cliente", "status", "produtos", "servicos",
  "composicoes", "execucoes", "tipo", "vendedor", "locacoes"];

want to ignore the object "products", how can I do this?

  • 1

    So what did you think of the solution.

1 answer

1

Develop a Scope to remove from the early interface the item or items:

public function scopeNoEagerLoadsExcept($query, array $items)
{
    if (count($items) == 0)
    {
        return $query;
    }

    $eagerLoads = $this->getEagerLoads();
    $keysEagerLoads = array_keys($eagerLoads);
    $with = array();
    foreach ($keysEagerLoads as $key)
    {
        if (!in_array($key, $items))
        {
            $with[$key] = $eagerLoads[$key];
        }
    }
    $query->setEagerLoads($with);
    return $query;
}

in that method makes a check if the item is inside the charge key in advance and removes the item in that Builder created, and it is worth remembering that after this result materialization the load goes back to being as before with all the configured relations that is very useful for the next researches where they need all the relations.

Example of use:

 ItemsProduct::noEagerLoadsExcept(['produtos'])->get();

Reading

Tip

If you want this model do not load the configured relations, ie no relation, use the method setEagerLoads([]), example:

ItemsProduct::setEagerLoads([])->get();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.