我有transactions table
我可以在其中存储多态关系,payment
或plan
。我似乎无法得到的是,当我更新现有交易时,我删除了表单中的payment_id
或plan_id
,如何从数据库中清除该关系。
插入(或更新)时,这样可以正常工作:
$payment->transactions()->save($transaction);
我尝试了很多东西,而detach
方法不起作用,因为它不是多对多关系。
我的模特:
交易:
public function paymentable()
{
return $this->morphTo();
}
付款(和计划):
public function transactions()
{
return $this->morphMany(Transaction::class, 'paymentable');
}
有什么想法吗?
基本上我的问题是这样,当我对现有交易执行更新时,如果未提交paymentable_id
或paymentable_type
,如何清除payment
和plan
?基本上,当从表单中删除payment
或plan
时。我不想使用某些RAW查询。
答案 0 :(得分:1)
用户@zgabievi的评论正确。 dissociate()
从5.0开始就存在。这是将其添加到MorphTo
关系中的提交:https://github.com/laravel/framework/commit/3d6727e1764c37e1219b0a1fc7e003ef61615434#diff-4c052acf0022213a4cc23f53ba42720e
我已使用此方法将多态文件记录与其父模型分离。因为它在MorphTo
中,所以在子级上调用了dissociate()
方法。
示例:
$attachment = new Attachment; // contains 'attachable' morphTo relationship
$note = new Note; // contains morphyMany relationship to Attachment
// save the Attachment through the attachments relationship, sets morph fields and persists to the database
$note->attachments()->save($attachment);
// populate the morph fields without saving
$attachment->attachable()->associate($note);
// clear the morph fields without saving
$attachment->attachable()->dissociate();