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?
Advertisement
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()