Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP: Bind Model not working

Tags:

cakephp

I have User HABTM Professions. In user edit, there is a list of checkboxes of professions. It was working when I defined the HABTM relationship in user model. But as that relationship was interrupting other functions I removed it and put this in user controller

$this->User->bindModel(
        array(
            'hasAndBelongsToMany' => 
            array(
                'Profession' =>
                    array(
                        'className'              => 'Profession',
                        'joinTable'              => 'professions_users',
                        'foreignKey'             => 'user_id',
                        'associationForeignKey'  => 'profession_id',
                        'unique'                 => true,
                        'conditions'             => '',
                        'fields'                 => '',
                        'order'                  => '',
                        'limit'                  => '',
                        'offset'                 => '',
                        'finderQuery'            => '',
                        'deleteQuery'            => '',
                        'insertQuery'            => ''
                    )
                )
            )
        );  

The return value of that binding function is also true.

Now when I call $this->User->saveAll($this->data), rows are not created in professions_users table anymore.

Any idea?

like image 318
Moe Sweet Avatar asked Feb 26 '23 18:02

Moe Sweet


1 Answers

The default behaviour of bindModel is to exist for one find operation, then revert to the default associations. You might think a save operation wouldn't trigger this, but if you use Cake's count-caching feature, or a Behaviour with an afterSave callback that performs a find, you might be wrong.

Try passing false as a second parameter of your Model::bindModel call. This will make your on-the-fly binding last the duration of the request. You can always explicitly reset the associations after your saveAll has completed by invoking Model::resetAssociations.

like image 135
Daniel Wright Avatar answered Mar 27 '23 11:03

Daniel Wright