1
votes

I have 3 tables

locationables    |locations     | account_doctor
-----------------+--------------+------------------+
**id**           |**id**        |**account_id**    |
location_id      |              |                  |
locationable_id  |              |                  |
locationable_type|              |                  |

would you please help me how can i write many to many polymorphic relationship between them?

I have read Laravel documentation but primary key of account_doctor table doesn't have standard conevtion cause of that relationship doesn't retrieve anything

this is my relations:

AccountDoctor model:

    public function locations()
    {
        return $this->morphToMany(Location::class, 'locationable','locationable');
    }

Location model:

public function accountDoctors()
    {
        return $this->morphedByMany(AccountDoctor::class, 'locationable','locationable');
    }
1
i have read this but primary key of account_doctor is not standard and cause of that relation doesn't retrieve anything - Farzane Khazaei
you can change the primary key of an Eloquent model - Flame
i added protected $primaryKey = 'account_id'; to model but still its not working - Farzane Khazaei
DB::enableQueryLog() ...dostuffhere dd(DB::getQueryLog()) or install laravel debugbar, or try out different parameters for the relation function - Flame
would you please right form of relationship for me tnQ - Farzane Khazaei

1 Answers

1
votes

The relationship definitions should be as below

class AccountDoctor extends Model
{
    public function locations()
    {
        return $this->morphToMany(
            Location::class, 
            'locationable',     //name for the morphable
            'locationables',    //pivot table
            'locationable_id',  //foreign key on the pivot table to identify this model record
            'location_id',      //foreign key on the pivot table to identify related model record
            'account_id',       //primary key column name for this model's table
            'id'                //primary key column name for related model's table
        );
    }
}

And

class Location extends Model
{
    public function account_doctors()
    {
        return $this->morphedByMany(
            AccountDoctor::class, 
            'locationable',     //name for the morphable 
            'locationables',    //pivot table 
            'location_id',      //foreign key on the pivot table to identify this model record 
            'locationable_id',  //foreign key on the pivot table to identify related model record 
            'id',               //primary key column name for this model's table
            'account_id'        //primary key column name for related model's 
        );
    }
}