0

I have 3 tables:

1) CourseA
2) CourseB
3) Orders

Here is the structure of CourseA table:

id | course_title 
1  | Maths
3  | Physics 

Here is the structure of CourseB table:

id | course_title 
2  | Biology
6  | Physcology

Here is the structure of Orders table:

id | course_id | course_type 
1  | 1         | 1
2  | 2         | 2

(Note: course_type == 1 means the record belongs to CourseA table, & course_type == 2 means the record belongs to CourseB table).

Now here in Orders table, course_id is a foreign key depending on 2 different tables.

How can I use Laravel Migration for this type of scenario?

I tired something like this but its not working:

Schema::table('orders', function($table)
{
    $table->foreign('course_type')->references('id')->on('courseA');
    $table->foreign('course_type')->references('id')->on('courseB');
});

Any idea what is wrong here?

StormTrooper
  • 1,731
  • 4
  • 23
  • 37

1 Answers1

0

You need to create a column then create foreign key in migration. It should be :

Schema::table('orders', function($table)
 {   
      $table->bigIncreaments('id'); // not necessary 

      $table->bigInteger('course_type_a')->unsigned();
      $table->foreign('course_type_a')->references('id')->on('courseA');

      $table->bigInteger('course_type_b')->unsigned();
      $table->foreign('course_type_b')->references('id')->on('courseB');

 });
STA
  • 30,729
  • 8
  • 45
  • 59
  • Can you please explain course_type_a & course_type_b? – StormTrooper Jun 17 '20 at 18:12
  • You want to insert `CourseA` and `CourseB` `id` on `orders` table in a same time with 2 row, right? If `CourseA` & `CourseB` id are same then how do you know which `id` is from `CourseA` and which from `CourseB`? Thats why create different column for store different table id. I hope you understand now? – STA Jun 17 '20 at 18:22
  • As you can see i already have a column with course_type followed by values 1 & 2 – StormTrooper Jun 19 '20 at 17:41
  • You want to make a column relation with 2 table. But you can just one column relation with 1 table, not 2. Hope this help you https://stackoverflow.com/questions/15547276/is-it-possible-to-reference-one-column-as-multiple-foreign-keys – STA Jun 19 '20 at 17:44