Facing exact same issue.
Any help by someone that has found out a solution for this would be extremely appreciated!
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.
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.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community