简体   繁体   中英

Laravel 5 detach / remove polymorphic relation

I've got a transactions table in which I can storea polymorphic relation, either payment or plan . What I cannot seem to get is, when I update an existing transaction, and I remove the payment_id or plan_id in the form, how to clear that relation from the database.

When inserting (or updating), this works fine:

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

I've tried a lot of things, and the detach method doesn't work, since it's not a many to many relation.

My models:

Transaction:

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

Payment (and Plan):

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

Any ideas?

Basically my question is this, how can I clear the paymentable_id and paymentable_type when I perform an update on an existing transaction, when no payment or plan was submitted? So basically, when the payment or plan was removed from the form. I prefer not to use some RAW query.

User @zgabievi's comment is correct. dissociate() has been around since 5.0. Here's the commit that added it to the MorphTo relationship: https://github.com/laravel/framework/commit/3d6727e1764c37e1219b0a1fc7e003ef61615434#diff-4c052acf0022213a4cc23f53ba42720e

I have used this method to dissociate polymorph files records from their parent model. Because it is in MorphTo , the dissociate() method is called on the child.

Example:

$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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM