Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable eager relations

In my project I have many Eloquent models that have eager relations configured in class like this:

protected $with = [ 'countries', 'roles' ];

But sometimes I need just old plain model without any relations. Can I somehow do:

Model::noRelations()->all()

Really don't wanna use query builder nor create another class just for few occasions.

like image 773
Yauheni Prakopchyk Avatar asked Dec 02 '15 20:12

Yauheni Prakopchyk


People also ask

What is lazy vs eager loading in Laravel?

Lazy Loading vs. Eager Loading. While lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.

What is Laravel eager loading?

Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.

How many types of relationships are there in Laravel?

It is basically the interconnection of different tables for data integrity and to avoid redundancy of data. It provides 3 main types of relationships and 2 intermediate types. Let's take a dive into each of these laravel relationships as we describe what they mean and how we can define them.

What is use of relationship in Laravel?

One to one relationship provides the one-to-one relationship between the columns of different tables. For example, every user is associated with a single post or maybe multiple posts, but in this relationship, we will retrieve the single post of a user.


2 Answers

If you have to set the $with property on your model rather than leaving it empty, you can manually override the relationships that need to be eager loaded like this:

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

Link to API for setEagerLoads

like image 112
Thomas Kim Avatar answered Nov 01 '22 22:11

Thomas Kim


In addition to Thomas Kim answer.

If you anyway extend Eloquent\Model class and often need to strip off relations from model, this solution might suit you well.

  1. Create scope in your default model class:

    public function scopeNoEagerLoads($query){
        return $query->setEagerLoads([]);
    }
    
  2. For any ORM, that extends that class you will be able to:

    User::noEagerLoads()->all()
    
like image 26
Yauheni Prakopchyk Avatar answered Nov 01 '22 23:11

Yauheni Prakopchyk