Support the ongoing development of Laravel.io →
Configuration Database Eloquent
Last updated 1 year ago.
0

Facing exact same issue.

Any help by someone that has found out a solution for this would be extremely appreciated!

Last updated 1 year ago.
0

detach() did not worked for me either, and I could not find the solution. So for me it was either remove the id and type from the specific node, or in my case, remove the related node its self.

With polymorphic relation, what happens is that when you do something like $content->xyz()->save($xyzNode), at the back end, the polymorphic fields of id and type get the id and type of the $content. There is no middle table here. So just removing the xyzNode using $xyzNode->delete() worked for me. In my case, I have Image model as polymorphic, and its related to Workshop model.

// image model
class Image extends \Eloquent {
    public function of() {
        return $this->morphTo();
    }
}
// workshop model
class Workshop extends Elegant {
    // polymorphic relation
    public function photos() {
        return $this->morphMany('Image', 'of');
    }

    // method to attach photos
    public function attachPhotos($newIds) {
        // remove existing photos which are not part of new ids
        foreach($this->photos as $photo) {
            if(!in_array($photo->id, $newIds)) {
                $this->_detachPhoto($photo);
            }
        }

        foreach($newIds as $id) {
            $image = Image::find($id);
            $this->photos()->save($image);
        }

    }

    // detach photos
    public function _detachPhoto($photo) {
        $photo->delete();
    }

}

As you can see above, _detachPhoto() method simple deletes the related image and the relation is automatically removed, as the $this->photos will return all content from images table, whose "id" and "type" fields have the related data of current node, which in my case is represented by $this.

Hope this helps.

If any one knows a formal way of doing it, I would appreciate if they can share here.

Last updated 1 year ago.
0

detach is for many-to-many relationships. It deletes the relationship pivot, not the related model. Your relationship does not appear to be many-to-many but rather polymorphic one-to-many, so you could just delete the related model.

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

pileq pileq Joined 6 Jun 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.