We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

How to delete Relationships between models Many To Many

I was created model as manyToMany like this

<?php
 $this->hasManyToMany('id',
              'Vokuro\Models\BannerSitePlace',
              'banner_id',
              'site_place_id',
              'Vokuro\Models\SitePlace',
              'id',
              array('alias' => 'places')
          );

On update entity after

<?php
  $banner->places = $places;
  $banner->save();// or ->update

The old relationships not deleted. If i try delete before save all data like

<?php
 foreach($banner->places as $place){
    $place->delete();
  }

Phalcon tried to delete "place" that related also to an anather model instead of to delete relationship. How delete only relationships?



144.9k
Accepted
answer
edited Sep '16
$placesIds = [1, 2, 3, 4];
$bannerPlaces = BannerSitePlace::find([
    'conditions' => 'banner_id = :id: AND site_place_id IN ({placesIds:array})',
    'bind' => [
        'id' => $id,
        'placesIds' => $placesIds
    ]
]);
$bannerPlaces->delete();

Easier can be just add hasMany relation with alias bannerPlaces. And then just $banner->bannerPlaces->delete();



17.5k

was added

$this->hasMany('id', 'BannerSitePlace', 'banner_id', array('alias' => 'BannerSitePlaces'));

and get error

Model 'BannerSitePlace' could not be loaded

Delete by find get error

A primary key must be defined in the model in order to perform the operation

Because you forgot an namespace - Vokuro\Models\BannerSitePlace. Well looks like just Vokuro\Models\BannerSitePlace don't have primiary key - add it then.



17.5k

all work in two ways after added primary autoincrement key