Laravel/Eloquent: How to create a primary key composed of two foreign keys?

Asked

Viewed 1,565 times

0

I am creating a simple system for school management and I will have a table called 'class students', where the primary key should be composed by the student id and class id, which are foreign keys of the 'students' and 'classes' tables respectively. I created my Migration as follows:

public function up()
{
    Schema::create('turma_alunos', function (Blueprint $table) {
        $table->integer('ID_TURMA_TUR')->unsigned();
        $table->foreign('ID_TURMA_TUR')->references('ID_TURMA_TUR')->on('turmas');
        $table->integer('ID_ALUNO_ALU')->unsigned();
        $table->foreign('ID_ALUNO_ALU')->references('ID_ALUNO_ALU')->on('alunos');
        $table->primary(['ID_TURMA_TUR', 'ID_ALUNO_ALU']);
        $table->timestamps();
    });
}

In the end, the table with the composite primary key was created, but only the student’s id was a foreign key:

Tabela criada após rodar a migration

Is it possible to do it the way I would like? How to do it in Laravel?

  • I decided to put an answer, maybe it helps to understand that the relationships were created correctly.

1 answer

2


The key in yellow in the phpmyadmin means primary key of your table, the key in gray means a index, example:

inserir a descrição da imagem aqui to know if the relationships were created correctly

and to know if it was really created the relations just click on Relation view:

inserir a descrição da imagem aqui

and both relationships have to appear (fictional example) like this example:

inserir a descrição da imagem aqui

thus it is correct, being them as primary keys of this table with relations in other tables.

  • Thank you very much! It is correct then the creation. What exactly would this index?

  • 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.