Eager load polymorphic relationships with constrain()
#6507
-
I’ve searched Nova docs, Laracasts, and this repo for a way to eager load polymorphic relationships using Currently, you can only eager load using the static public static function with()
{
return [
'model' => function ($morphTo) {
$morphTo->constrain([
\App\Models\Foo::class => function ($query) {
$query->with(['relation']);
},
\App\Models\Bar::class => function ($query) {
$query->with(['different_relation']);
},
\App\Models\Baz::class => function ($query) {
// No eager loading necessary
}
]);
}
];
} I noticed that public static function with($relations)
{
return static::query()->with(
is_string($relations) ? func_get_args() : $relations
);
} I needed this because I have models where I want to eager load a Perhaps I'm looking in the wrong places. If you know of another solution, I’m open to suggestions. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I can't believe I completely forgot the existence of the public static function indexQuery(NovaRequest $request, $query): Builder
{
return parent::indexQuery($request, $query)
->with([
'model' => function ($morphTo) {
$morphTo->constrain([
\App\Models\Foo::class => function ($query) {
$query->with(['relation']);
},
\App\Models\Bar::class => function ($query) {
$query->with(['different_relation']);
},
\App\Models\Baz::class => function ($query) {
// No eager loading necessary
}
]);
}
]);
} |
Beta Was this translation helpful? Give feedback.
I can't believe I completely forgot the existence of the
indexQuery()
method.I used the following for eager loading: