oliver oliver - 5 months ago 32
PHP Question

Associated Delete in CakePHP 2.5.4

I have 2 entities in the database Element and Section.

1 section has 0-N elements so in the element table I have a foreign key

CONSTRAINT `elements_sections` FOREIGN KEY (`section_id`) REFERENCES `sections` (`id`) ON UPDATE CASCADE ON DELETE CASCADE


Element Model .php has this:

public $belongsTo = array(
'Section' => array(
'className' => 'Section',
'foreignKey' => 'section_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);


In the Section model I have:

public $hasMany = array(
'Element' => array(
'className' => 'Element',
'foreignKey' => 'section_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);


All this code looks good, however, when I delete an element of the section with ID=X, if there's an element (in any other section) with ID=X that element is deleted too. This is the code I am using in my whole aplication but only fails here. $this->data is the Element object.

$this->Element->delete($this->data)


A detailed example:

Section 20 -> Element 400
Section 3 -> Element 20

If I delete the element 400, the Element 20 is deleted too.

I guess that I am missing a configuration parameter or some.

Thanks in advance.

Answer

For somebody that can face the same problem this could help:

Model::delete() can delete multiple records.

[
    'id' => 1,
    'category_id' => 3,
    'price' => 10000,
]

Will generate

DELETE FROM elements WHERE id IN (1, 3, 10000).