Laravel 5.2 - Making Many To Many relationships between records of the same table

2

The tables:

  • The users table registers users who can have N functions that are stored in the funcoes table (student, responsible, teacher, etc.).
  • The funcao_user table is pivot that makes the Many To Many relationship between users and funcoes .

So far, everything okay.

A user who has a student role can have N users with the role of respon- sible, and a user who has the role of responsible for having N users with the student role, ie there is a Many To Many relationship within of the users table.

For this relationship, I created the pivot table aluno_responsavel with the fields: aluno_id , responsavel_id and parentesco (in relation to the parent, indicate parent, etc):

 Schema::create('aluno_responsavel', function (Blueprint $table) {
     $table->integer('aluno_id')->unsigned();            
     $table->integer('responsavel_id')->unsigned();
     $table->string('parentesco');
     $table->foreign('aluno_id')->references('id')->on('users')->onDelete('cascade');
     $table->foreign('responsavel_id')->references('id')->on('users')->onDelete('cascade');
});

How would the relationship between the users and aluno_responsavel tables in the User model be?

    
asked by anonymous 14.09.2016 / 22:34

2 answers

0

With the information found in link I made the following relationship in the model and it worked (to simplify the tests, I left the kinship column outside):

public function responsaveis()
{
     return $this->belongsToMany('App\User', 'aluno_responsavel', 'aluno_id', 'responsavel_id');
}

With this, I can store the aluno_id and responsavel_id ids with the following command in the controller:

$user->responsaveis()->attach($request->responsavel_id);

But, I still need to know how to retrieve the values stored in the pivot table. I made this attempt, but it does not bring the expected data:

$userAluno = User::find($user_id);

foreach ($userAluno->responsaveis as $responsavel) {
     echo $responsavel->responsavel_id . <br />;
}
    
16.09.2016 / 19:55