Withrelatedbehavior Help

From browsing the forum I came across the WithRelatedBehavior extension but I’m struggling to figure out how to update the join tables when you re-save an object with a MANY_MANY relationship.

I’m currently populating a class var with an array of ID’s via a checkboxList, but saving with the related attribute populated with a new array of related objects doesn’t seem to affect the join table, is this not a feature or is it something I am doing wrong?

Thanks in advance for any help, code snippet below:


/**

		 * populate the relation with the necessary objects for the many/many save

		 * @param  [string] $classArr [the related id's]

		 * @param  [string] $class [the related object class name]

		 * @param  [string] $relation [the name of the relation attribute]

		 * @return [type]           [description]

		 */

		public function prepareMany($classArr, $class, $relation){

			$manyObjs = array();

			

			//must be an array, if not it is probably an empty string

			if(!is_array($this->owner->$classArr)){

				$this->owner->$classArr = array();

			}


			if(is_array($this->owner->$classArr)){


				foreach($this->owner->$classArr as $id){


	        		$obj = call_user_func(array($class,'model'));

	        		$manyObjs[] = $obj->findByPk($id);

				

				}	        	


				$this->owner->$relation = $manyObjs;


			}else{

				throw new Exception('the class var holding the many ID\'s ('.$classArr.') needs to be an array');

			}

		}

Looks like this functionality doesn’t exist but I’ve come up with a solution for anybody else who has this issue, below is what has changed from my snippet above:


			if(is_array($this->owner->$classArr)){


				//if no longer in the list it still needs to be sent but with a remove flag of 1

				foreach($this->owner->$relation as $r){

					if(!in_array($r->id,$this->owner->$classArr)){

						$r->remove = 1;

						$manyObjs[] = $r;

					}

				}


				foreach($this->owner->$classArr as $id){


	        		$obj = call_user_func(array($class,'model'));

	        		$manyObjs[] = $obj->findByPk($id);

				

				}	        	


				$this->owner->$relation = $manyObjs;


			}else{

				throw new Exception('the class var holding the many ID\'s ('.$classArr.') needs to be an array');

			}

Then add the following to line 346 of WithRelatedBehavior.php:


							/**

							 * Custom Edit - allow for delete of relation on update if de-selected

							 */

							if(!$model->remove)

								$insertAttributes[]=$joinTableAttributes;

N.B - I believe this could be made more efficient by only adding an object to the owner->$relation that doesn’t already exist in the relation rather than creating a whole new list with findByPk($id) every time, just haven’t got round to sorting it out yet.