How to Eager Loading Specific Columns for Polymorphic
relation?
#52292
Unanswered
siarheipashkevich
asked this question in
Q&A
Replies: 2 comments 1 reply
-
You can use contraint : https://laravel.com/docs/10.x/eloquent-relationships#constraining-eager-loading-of-morph-to-relationships |
Beta Was this translation helpful? Give feedback.
1 reply
-
For non morph relations this works: $builder->with('rel', function(Relation|Builder $query): void {
$query->select(['col']);
}); You can try: $banners = Banner::with(['bannerable' => function (MorphTo $morphTo) {
$morphTo->constrain([
Agency::class => fn($q) => $q->select(['id', 'title'])->orderBy('title'),
Site::class => fn($q) => $q->select(['id', 'name'])->orderBy('name'),
])->select(['id', 'name']); // maybe you have to qualify the selected columns.
}])->get(); 'items.item' => function (MorphTo $morphTo) {
// It's needed for determining the item is weight or not by unit.
$morphTo->morphWith([
Product::class => ['unit'], // <<< but, how to include only id and name columns for product model?
Ingredient::class => ['unit'], // <<< but, how to include only id and name columns for ingredient model?
])->select(['id', 'name']); // maybe you have to qualify the selected columns.
}, Bear in mind that you NEED to get the column that links the relation to the model for the eager loading to match the relation row with the model. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
https://laravel.com/docs/11.x/eloquent-relationships#eager-loading-specific-columns
Is anybody trying to specify columns for polymorphic relations?
Beta Was this translation helpful? Give feedback.
All reactions