php - laravel many to many polymorphic relationship with custom foreign key
Get the solution ↓↓↓I have 3 tables
locationables |locations | account_doctor
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:
{-code-2}
Location model:
{-code-3}
Answer
Answer
Solution:
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
);
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: to enable extensions, verify that they are enabled in your .ini files
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.