I'm currently working on laravel framework and I'm stuck with some relations and eager loading issues.
I have three models A, B and C
I have two relations
By default (using the $with attribute in Model) :
So most of the time I'm using A without B and B with C
And here is how I've set up the relationship methods & eager loading
class A extends Model {
...
protected $with = [];
public function bs() {
return $this->hasMany('App\Models\B');
}
}
class B extends Model {
...
protected $with = ['cs'];
public function cs() {
return $this->hasMany('App\Models\C');
}
public function a() {
return $this->belongsTo('App\Models\A');
}
}
class C extends Model {
...
public function b() {
return $this->belongsTo('App\Models\B');
}
}
For a specific task I'd like to query A with all B and without any C
When I'am using A::query()->with('b')
C are loaded by default
So I'am trying to use A::query()->with('b')->without('b.c')
But it keep loading B to C relations.
Have you any idea on how to achieve this ?
Thanks for your help !
As of Laravel 5.8.22 (2019-06-12) there’s a new morphWith method and to load nested relations with Eager Loading you can use: This code reads as For all the Installments load the methodable relation. For those, if the loaded Model is a InstallmentBt then load the info relation as well.
Laravel’s ORM, called Eloquent, makes it trivial to eager load models, and even eagerly loading nested relationships. Let’s build on the Post model example and learn how to work with eager loading in a Laravel project.
In this example, Eloquent will only eager load posts that have not been hidden and videos have a type value of "educational". Sometimes you may need to eager load a relationship after the parent model has already been retrieved. For example, this may be useful if you need to dynamically decide whether to load related models:
The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation. For example, let's assume we are building a deployment platform like Laravel Vapor. A Project model might access many Deployment models through an intermediate Environment model.
The Eloquent\Model
has a newQueryWithoutRelationships
.
I think you could do the following:
(new A())->newQueryWithoutRelationships()->with(...)
Update after comment
Interesting method without()
(did not know about it).
It looks like you could try the following:
A::query()->with(['bs' => function($query) {
$query->without('c');
}]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With