bikash.bilz
bikash.bilz

Reputation: 821

Issue in hasMany associated model data update/modify

I have two table,
categories     hasMany products
id
name
active

products       belongsTo categories
id
name
category_id
active

When I am editing the categories, in the same time I am also displaying the Products related to the category so that I can update/modify products related to the category.

Issue:- When I add more products for the category that works fine but when I remove some products from the category,the removed product does not get deleted from the database. So I want to know that This functionality is supported by CakePHP or not. If yes please help me to find where I am going wrong.

Here is the save code:-

$categoryProducts = $this->Categories->get(1, [
   'contain' => 'Products' 
]);

    if($this->request->is['post', 'put']){
       $entity = $this->Categories->patchEntity($categoryProducts, $this->request->data);


      $this->Categories->save($entity);

}

Upvotes: 0

Views: 300

Answers (1)

Greg Schmidt
Greg Schmidt

Reputation: 5099

When you set up your hasMany relationship, add 'saveStrategy' => 'replace'. See the hasMany section of the manual for details.

Upvotes: 3

Related Questions