Help with MANY to MANY relationship deleting a record

I am having a hard time working with a many to many relationship. I have three tables (customer, customer_assignment and owner). Obviously, customer can have many owners and owners can have many customers. I am trying to remove a owner from a customer; however, the logic I have removes all owners from the customer and not just the single record(owner). My code is posted below:

Model:




public function relations()

	{

           return array(

            'customerAssign' => array(self::HAS_MANY, 'CustomerAssignment', 'customer_id'),

            'owner' => array(self::MANY_MANY, 'Owner', 'tbl_customer_assignment(id, customer_id)'),

	    );

	}



Controller:




public function actionRemoveOwner($id)

	{ 

                $model=$this->loadModel($id);

                

                foreach($model->owner as $ownerID)

                                

                CustomerAssignment::model()->find("id = '$ownerID->id'")->delete();

                        

                Yii::app()->user->setFlash('success', "Owner Successfully Removed." );

            

                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('view','id'=>$id));

                               

	}



I am new to Yii and really would appreciate someone reaching out to help.

Check which records are returned by:


$model->owner

Those are the only records being removed.

Thanks Asgaroth.

Fixed.

Attach delete to an instance. For those that may need help with this here is what I did:




public function actionRemoveOwner($id)

        { 

                $model=$this->loadModel($id);

                

                foreach($model->owner as $ownerID)

                                

                $ownerDelete = CustomerAssignment::model()->find("id = '$ownerID->id'");

                $ownerDelete->delete();

                        

                Yii::app()->user->setFlash('success', "Owner Successfully Removed." );

            

                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('view','id'=>$id));

                               

        }



uppp

solved??

Mind me from not reading the use case deeply - but how about creating constraints in the DB level that will “cascade” when an entry in either customer or owner are being deleted? This can propagate the deletion to the ‘linking table’ automatically for you.