Relationship With The Same Table (Many To Many?) - Laravel
In my database I have to save people and the data of people that have a relationship with the first. For example: father, mother, son, daughter, etc
Then the design of the database, I did it in the following way Is a relation many-to-many because, a person have many people related to it.
But I'm not sure if is ok..
class Person extends Model
{
protected $fillable = [
'name',
'surname',
'profile_picture'
.....
];
public function relationships()
{
return $this -> belongsToMany(Person::class);
}
}
When I create the relation I create a thirth migration table call person_person to save the ids and a description (father, mother, son, daughter)
it's ok describe the relationship this way?
public function relationships()
{
return $this -> belongsToMany(Person::class);
}
What should I add to complete successful this relationship?
Answer
You'll need to define the table, primary and foreign key, as Laravel likely can't determine this (it'll try, but it probably won't succeed). Something like:
public function relationships(){
return $this->belongsToMany(Person::class, "person_person", "id_person", "id_person_related")
->withPivot(["parentesco"]);
}
or similar. Table name is a bit awkward, consider something else, like 'relationships'
or something that conveys more meaning.
See https://laravel.com/docs/5.8/eloquent-relationships#many-to-many for details on how to define additional parameters for belongsToMany()
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?