Laravel的mysql数据分离想法
问题产生
good_orders表 (商品订单表)(已支付成功了的订单)
addr_id 关联的地址表id
good_id 关联商品表id
user_id 关联的用户表id
....
goods (商品表)
title 名字
img 封面
price 价格
....
addresses (地址表)
......
- 如果运维修改
商品 (goods)
,那么商品订单表
随之受到影响。 - 用户修改
地址 (address)
,那么地址也会随之受到影响。
如何避免这种情况 ?
(普遍解决方案: 就是商品订单表增加字段 good_data
address_data
,用json
存储….)
我的解决方案
创建 good_orders
时,
新增一条goods
数据 和 addresses
数据。
然后修改关联的字段。 (good_id
和addr_id
)
实现 (勿直接用 看最后面的”待优化”)
新建一个类
<?php
namespace App\Services;
trait ModelTrait
{
public function copy($remote)
{
if( $this->$remote == null) // 模型关联不存在
return true;
$new_model = clone $this->$remote; //mo'b 要新增的数据
$primaryKey = $new_model->getKeyName(); // 主键
$new_model->$primaryKey = null; // 要把主键设置为null,不能存在两个相同的数据
$new_model->exists = false; // 设置为false才会新增 true会修改
if( $new_model->save()){ // 新数据保存成功
$foreignKey = $this->$remote()->getForeignKeyName();
$this->$foreignKey = $new_model->id;
// 修改关联的外键值 如(`good_id` `addr_id`)
return $this->save();
}
return false;
}
}
使用 use
测试
测试前 (goods表截不全 )
测试后 (goods表截不全)
待优化 (需自行实现)
很多条数据怎么办?
运维
: 怎么突然多这么多的商品!用户
: 怎么突然多这么多的地址!
解决思路: 加个软删除
或者 status
是否显示……
造成数据表很大?
那就建立一个 goods_tmp
addresses_tmp
表呗
订单查询的时候, 往goods_tmp
addresses_tmp
去查。
(是否有必要而已)
本作品采用《CC 协议》,转载必须注明作者和本文链接
推荐文章: