Reputation: 1993
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.
Upvotes: 1
Views: 3650
Reputation: 2016
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();
Upvotes: 1