MainelyDesign.com Blog

Delete Dependent Just Deleted All My Records

Posted on 09/17/2009 at 10:12 am by Kevin Wentworth
Viewed 13,537 times | 0 comments

Oh man! I just deleted all my database records using $model->del($id) with dependent=>true in the model association.  That wasn't supposed to happen!  It turns out to be an issue with how I specified my model association.  What's weird is that everything works fine except when I go to do the delete with cascade set to true.

Use an array for conditions when associating models

I was using some older model code and never changed it because everything worked fine.  However, the issue came down to not using an array for my conditions within the model association.  I have a model gallery that hasMany images and is dependent.  Below is the old code and the new code:

Bad code (note the conditions string):

  1. class Gallery extends AppModel {
  2.  
  3.     var $name = 'Gallery';
  4.     var $hasMany = array(
  5.         'Image' => array
  6.         (
  7.             'className' => 'Image',
  8.             'order' => 'Image.sort_order ASC',
  9.             'foreignKey' => 'type_id',
  10.             'conditions' => "Image.type = 'gallery'", //BAD!
  11.             'dependent' => true
  12.         ),
  13.     );  
  14.    
  15. }

Good code (note the conditions array):

  1. class Gallery extends AppModel {
  2.  
  3.     var $name = 'Gallery';
  4.     var $hasMany = array(
  5.         'Image' => array
  6.         (
  7.             'className' => 'Image',
  8.             'order' => 'Image.sort_order ASC',
  9.             'foreignKey' => 'type_id',
  10.             'conditions' => array('Image.type' => 'gallery'), //GOOD!
  11.             'dependent' => true
  12.         ),
  13.     );  
  14.    
  15. }

Array_merge() error in model.php at line 1763

The issue is that CakePHP wants to merge the conditions array with the existing conditions.  That's why your model association conditions MUST be an array.

Cheers,

-Kevin Wentworth

 

Bookmark and Share

Tags for Delete Dependent Just Deleted All My Records

Cakephp | Web Programming | Mysql | Usage | Database

Comments for this Posting

No comments. Be the first to post a reply.

Sorry, comments are closed for this posting.

Please Email Kevin if you have any questions. Thanks!

Meet Site Avenger - Hosted Content Management System

Powered By: Site Avenger | Site Production: Saco Design