#Problem with automaticallyEagerLoadRelationships and Morph Relationships

2 messages · Page 1 of 1 (latest)

fading abyss
#

I currently have the following problem, when i activate automaticallyEagerLoadRelationships in my Laravel Application. I have the following morphTo relation:


namespace App\Models\Tenant;

use App\Models\Base\VersionTable;
use Illuminate\Database\Eloquent\Relations\MorphTo;

class ProductVersion extends VersionTable
{
    protected $table = 'tenant_product_versions';

    public function product(): MorphTo
    {
        return $this->morphTo(
            'model_data',
            'tenant_product_type',
            'tenant_product_id',
            'id'
        );
    }
}

With automaticallyEagerLoading activated i get:
ProductVersion::with('product')->first()->product => null
ProductVersion::first()->product => null

It only works if i do it for example like this:
ProductVersion::first()->product()->first() => MODEL (expected result)

I have no clue why, disabling automaticallyEagerLoadRelationships also fixes the issue..does someone by any chance know what i am missing here?

ripe sundial
#

Without any example for me to work off (no nearby polymorphic relationships to play with)... here's my go at it:

The first 2 are just single queries and it doesn't know what tenant_product_type will resolve to.
The second one resolves as 2 queries, first getting the productversion and then looking for the product based on that id.

For a single line solution I think you want this: https://laravel.com/docs/12.x/eloquent-relationships#nested-eager-loading-morphto-relationships

$product = ProductVersion::query()
    ->with(['product' => function (MorphTo $morphTo) {
        $morphTo->morphWith([
            ProductType1::class => ['calendar'], // nested rels for this type
            ProductType2::class => ['tags'],
            ProductType3::class => ['author'],
        ]);
    }])
    ->first()->product;

Give that a try and let me know if my test-less research worked.
At this level of complexity with ORM I go nearly all custom queries. It's not the ORM can't do but it rarely works the way I want or expect, and is nearly as complicated as the raw queries themselves.

Laravel is a PHP web application framework with expressive, elegant syntax. We’ve already laid the foundation — freeing you to create without sweating the small things.