注意。 Also posted on Database Administrators
我有一张记录所有销售的表和十四个补充表,其中包含有关销售的额外信息。十四个补充表的所有意图和目的都是相同的。它们是很久以前创建的,当时最初的开发人员认为会有更多差异,但实际上现在项目已经成熟,它们的相似之处多于不同之处。然而它们是不同的,因此我需要将它们分开。
当前结构
销售表
| 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\SuppTwo
| id | customer_id | customer_ref | ... |
|-------|-------------|--------------|-----|
| 90488 | 867 | ref89b72 | ... |
| 90489 | 1024 | 0000080992 | ... |
| ... | ... | ... | ... |
表上没有外键将销售表连接到补充表,但有一个“customer_id”和“customer_reference”,它们对于销售表和补充表来说都是唯一的,但它们不一致。这是当前当我需要获取有关给定销售的更多信息时用来连接两个的内容。
我正在使用 Laravel 5.1 和 MySQL 数据库,我想向 sales 表添加两个字段; Supplemental_id 和 Supplemental_type 以便快速有效地创建多态关系。
所需的结构
销售表
| 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 中处理从 table_name 到 App\ClassName 的映射。 sales 表中有大约 150 万条记录,循环遍历它们将花费相当多的时间。
最佳答案
字里行间的东西。
它可能会覆盖特定销售记录的数据(即 SuppFourteen 覆盖 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,
]);
}
关于mysql - 使用 SQL 将补充表中的 ID 和类型添加到父表(MySQL 和 Laravel 多态关系),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51776685/