使用sql(mysql&laravel多态关系)将补充表中的id和type添加到父表中

tquggr8v  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(314)

注意。也发布在数据库管理员上
我有一个表,记录所有的销售和14个补充表,其中包含额外的销售信息。这十四个补充表格的目的和目的是相同的。它们是在很早以前创建的,当时最初的开发人员认为会有更多的差异,但实际上现在项目已经成熟了,它们更相似而不是不同。但是它们是不同的,因此我需要把它们分开。

当前结构

销售表

  1. | id | customer_id | customer_ref | ... |
  2. |---------|-------------|--------------------------------------|-----|
  3. | 1237567 | 354 | a6143f8c-b679-47be-9bc0-52457842913c | ... |
  4. | 1237568 | 867 | ref89b72 | ... |
  5. | ... | ... | ... | ... |

补充表1类:app\suppone

  1. | id | customer_id | customer_ref | ... |
  2. |------|-------------|--------------------------------------|-----|
  3. | 2857 | 10372 | 2016-07-01-ab5d09cc37ca | ... |
  4. | 2858 | 354 | a6143f8c-b679-47be-9bc0-52457842913c | ... |
  5. | ... | ... | ... | ... |

补充表2类:app\suppltwo

  1. | id | customer_id | customer_ref | ... |
  2. |-------|-------------|--------------|-----|
  3. | 90488 | 867 | ref89b72 | ... |
  4. | 90489 | 1024 | 0000080992 | ... |
  5. | ... | ... | ... | ... |

表上没有用于将sales表连接到补充表的外键,但是sales表和补充表都有唯一的“customer\u id”和“customer\u reference”,但它们不一致。这是什么是目前用来加入这两个当我需要得到更多的信息,关于一个给定的销售。
我使用的是laravel5.1和mysql数据库,我想在sales表中添加两个字段;补充的\u id和补充的\u类型,以便快速有效地创建多态关系。

所需结构

销售表

  1. | id | supplemental_id | supplemental_type | customer_id | customer_ref | ... |
  2. |---------|-----------------|-------------------|-------------|--------------------------------------|-----|
  3. | 1237567 | 2858 | App\SuppOne | 354 | a6143f8c-b679-47be-9bc0-52457842913c | ... |
  4. | 1237568 | 90488 | App\SuppTwo | 867 | ref89b72 | ... |
  5. | ... | ... | ... | ... | ... | ... |

我需要将这两个字段添加到每个销售记录中,但我不确定如何使用原始sql执行此操作,因为我预计这将比在迁移中执行要快得多。我想知道在sql中如何(如果可能的话)处理从表\u name到app\classname的Map。在sales表中有大约150万条记录,循环遍历它们不会花费不多的时间。

f45qwnt8

f45qwnt81#

在两条线之间的东西。
它可能会覆盖特定销售记录的数据(即SUPPREvent覆盖suppone数据),但在您的问题中就是这样表示的。

  1. $fourteen_tables = [
  2. 'supplemental_table_1' => App\SuppOne::class,
  3. // ...
  4. ];
  5. foreach ($fourteen_tables as $table => $class) {
  6. DB::table('sales_table')
  7. ->join($table, function ($join) use ($table) {
  8. $join->on($table.'.customer_id', '=', 'sales_table.customer_id')
  9. ->on($table.'.customer_ref', '=', 'sales_table.customer_ref');
  10. })
  11. ->update([
  12. 'sales_table.supplemental_id' => DB::raw($table.'.id'),
  13. 'sales_table.supplemental_type' => $class,
  14. ]);
  15. }
展开查看全部

相关问题