Tadas Davidsonas
Tadas Davidsonas

Reputation: 1929

Cakephp changing database foreign key field from user.id to users.id gives error in select statement

Cakephp changing database foreign key field from user.id to users.id gives error like when I want to get SELECT data with find() method:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Model.user_id' in 'where clause'

Even if in controller of the model in find method I use:

find( 'all', array 'conditions' => array('Model.users_id' => $userId)

I thought it was cache but clearing cache->models directory does not help.

Upvotes: 0

Views: 703

Answers (1)

Nik Chankov
Nik Chankov

Reputation: 6047

Even though you specifying the conditions in the find, the tables are related in the models. More over if the Model.users_id is defined in beloingsTo array in the primary model it will try to find the related records.

Let's say you have Post and User. Post belongs to User (Author) In that case you have in Post model a definition:

$belongsTo = array('User'=>array(...));

While in the User you have

$hasMany = array('Post'=>array(...));

If you were using the short syntax like:

$belongsTo = array('User');

It will search for foreign keys like user_id.

To achieve the find without errors, you need to set $this->Post->recursive = 0; or by using Containable by setting 'contain'=>array like:

$this->Post->find('all', array(
       'conditions'=>array('Model.users_id'=>(int)$user_id), 
       'contain'=>array()
));

This way relational tables won't be picked, but I would suggest to define the relational column in the model definition or change the column to user_id - that's why Cake is easy to understand - because it have strict naming DB convension and everyone which know them can understand the logic easily.

Upvotes: 1

Related Questions