Home > Mobile >  Problem with Polymorphic Relationships in Laravel
Problem with Polymorphic Relationships in Laravel

Time:05-20

I'm trying to implement a way to get the details of a person depending on the group it belongs to. My database looks like this: persons:

id group type
1 person 9
2 company 30
3 person 9

and so on.

Each "group" has a model which contains detail information for this record specific to the group.

For example:

persondetails looks like this

id person_id firstname lastname birthname
1 1 Harry Example Bornas
2 3 Henrietta Example Bornas

I created models for each table and I'm no trying to implement a relationship which allows me to query a person->with('details') via the person model (for example: for a complete list of all persons no matter which type it is). For single records I got it working via a simple "if $this->group === person {$this->hasOne()}" relation, which doesn't work for listings.

I tried to wrap my head around a way to use a polymorphic relationship, so I put the following into the person model:

 public function details(){
        Relation::morphMap([
            'person' => 'App\Models\Persondetail',
            'company' => 'App\Models\Companydetail',
        ]);
        return $this->morphTo();
    }

and a subsequent

public function person(){
        return $this->morphMany(Person::class, 'details');
    }

which doesn't work sadly. Where is my thinking error?

CodePudding user response:

As you're not using laravel convention for the keys, you need to define the keys on your relation

public function details()
{
    Relation::morphMap([
         'person' => 'App\Models\Persondetail',
         'company' => 'App\Models\Companydetail',
    ]);
    return $this->morphTo(__FUNCTION__, 'group', 'type');
}

Docs Link:

https://laravel.com/docs/9.x/eloquent-relationships#morph-one-to-one-key-conventions

CodePudding user response:

Based on the reply by https://stackoverflow.com/users/8158202/akhzar-javed I figure it out, but I had to change the code a bit:

Instead of the code in the answer, I had to use the following:

     public function details()
        {
            Relation::morphMap([
                'person' => 'App\Models\Persondetails',
                'company' => 'App\Models\Companydetail',
            ]);
            return $this->morphTo(__FUNCTION__, 'group', 'id', 'person_id');
        }
  • Related