【问题标题】:Laravel migration same foreign key dependency on 2 different tablesLaravel 迁移相同的外键依赖于 2 个不同的表
【发布时间】:2020-06-17 17:36:55
【问题描述】:

我有 3 张桌子:

1) CourseA
2) CourseB
3) Orders

这是CourseA表的结构:

id | course_title 
1  | Maths
3  | Physics 

这是CourseB表的结构:

id | course_title 
2  | Biology
6  | Physcology

这是Orders表的结构:

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

注意: course_type == 1 表示该记录属于CourseA 表,& course_type == 2 表示该记录属于CourseB 表)。

现在在 Orders 表中,course_id 是取决于 2 个不同表的外键。

在这种情况下如何使用 Laravel Migration?

我厌倦了这样的东西,但它不起作用:

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

知道这里有什么问题吗?

【问题讨论】:

  • CourseA和CourseB有什么区别?为什么不将它们合并到一个表中?
  • @JamesClarkDeveloper 实际上他们有不同的属性,这就是为什么

标签: php mysql laravel


【解决方案1】:

您需要创建一个column,然后在迁移中创建外键。 应该是:

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');

 });

【讨论】:

  • 你能解释一下 course_type_a 和 course_type_b 吗?
  • 您想在orders 表上同时插入CourseACourseB id 2 行,对吗?如果CourseACourseB id 相同,那么你怎么知道哪个id 来自CourseA,哪个来自CourseB?这就是为什么创建不同的列来存储不同的表 ID。我希望你现在明白了吗?
  • 如您所见,我已经有一个带有 course_type 的列,后跟值 1 和 2
  • 您想与 2 个表建立列关系。但是您可以只与 1 个表的一列关系,而不是 2 个。希望这对您有帮助 stackoverflow.com/questions/15547276/…
猜你喜欢
  • 1970-01-01
  • 2020-01-05
  • 2019-03-22
  • 2021-12-30
  • 2021-12-13
  • 2017-06-05
  • 1970-01-01
  • 2015-03-02
  • 2018-07-21
相关资源
最近更新 更多