[英]Laravel 5 detach / remove polymorphic relation
我有一个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');
}
有任何想法吗?
基本上我的问题是这样的,当我对现有交易执行更新时,没有提交payment
或plan
时,如何清除paymentable_id
和paymentable_type
? 所以基本上,当payment
或plan
从表单中删除时。 我不喜欢使用一些 RAW 查询。
用户@zgabievi 的评论是正确的。 dissociate()
从 5.0 开始就已经存在了。 这是将它添加到MorphTo
关系的提交: https : //github.com/laravel/framework/commit/3d6727e1764c37e1219b0a1fc7e003ef61615434#diff-4c052acf0022213a4cc23f503e42
我已经使用这种方法将多态文件记录与其父模型分离。 因为它在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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.