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

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

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

当前结构

销售表

| id      | customer_id | customer_ref                         | ... |
|---------|-------------|--------------------------------------|-----|
| 1237567 | 354         | a6143f8c-b679-47be-9bc0-52457842913c | ... |
| 1237568 | 867         | ref89b72                             | ... |
| ...     | ...         | ...                                  | ... |

补充表1类:app\suppone

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

补充表2类:app\suppltwo

| id    | customer_id | customer_ref | ... |
|-------|-------------|--------------|-----|
| 90488 | 867         | ref89b72     | ... |
| 90489 | 1024        | 0000080992   | ... |
| ...   | ...         | ...          | ... |

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

所需结构

销售表

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

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

f45qwnt8

f45qwnt81#

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

$fourteen_tables = [
    'supplemental_table_1' => App\SuppOne::class,
    // ...
];

foreach ($fourteen_tables as $table => $class) {
    DB::table('sales_table')
        ->join($table, function ($join) use ($table) {
            $join->on($table.'.customer_id', '=', 'sales_table.customer_id')
                ->on($table.'.customer_ref', '=', 'sales_table.customer_ref');
        })
        ->update([
            'sales_table.supplemental_id' => DB::raw($table.'.id'),
            'sales_table.supplemental_type' => $class,
        ]);
}

相关问题