场景:两张表,1会员卡主表,2,会员卡商品表,修改会员卡主表如果商品新增或者修改了,需要更新或者新增数据:
使用:
会员卡主表模型多对多关联副表
主表model:
//数据表名称
protected $table = 'saas_member_card';
/**
* 指示是否自动维护时间戳
*
* @var bool
*/
public $timestamps = false;
/**
* 多对多 批量修改新增数据使用
* @return BelongsToMany
*/
public function cardProduct():BelongsToMany
{
return $this->belongsToMany(SaasMemberCardProduct::class,'saas_member_card_product','card_id','product_id');
}
业务逻辑:
// 根据id查询主表
$card_first = SaasMemberCard::selectById($postData['id'])->first();
// 组装副表的数据 $free_product_id = [1,3,4,5]
$product_data = [];
foreach ($free_product_id as $value){
$product_data[$value] = [
'vip_type'=>1,
'custom_id'=>$this->custom_id,
'create_time'=> time(),
'product_id'=>$value
];
}
// 调用model的多对多使用sync更新或者修改数据
$card_first->cardProduct()->sync($product_data);