Laravel 5分离/删除多态关系

时间:2017-02-04 20:04:20

标签: php laravel polymorphism relation detach

我有transactions table我可以在其中存储多态关系,paymentplan。我似乎无法得到的是,当我更新现有交易时,我删除了表单中的payment_idplan_id,如何从数据库中清除该关系。

插入(或更新)时,这样可以正常工作:

$payment->transactions()->save($transaction);

我尝试了很多东西,而detach方法不起作用,因为它不是多对多关系。

我的模特:

交易:

public function paymentable()
{
    return $this->morphTo();
}

付款(和计划):

public function transactions()
{
    return $this->morphMany(Transaction::class, 'paymentable');
}

有什么想法吗?

基本上我的问题是这样,当我对现有交易执行更新时,如果未提交paymentable_idpaymentable_type,如何清除paymentplan ?基本上,当从表单中删除paymentplan时。我不想使用某些RAW查询。

1 个答案:

答案 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();