ItGo.me Focus on IT Recommend

Home > 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 in select statement

2020腾讯云双十一活动,全年最低!!!(领取3500元代金券),
地址https://cloud.tencent.com/act/cps/redirect?redirect=1074

【阿里云】双十一活动,全年抄底价,限时3天!(老用户也有),
入口地址https://www.aliyun.com/1111/home

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.

cakephp select model controller
asked Sep 9 '13 at 11:50 Tadas Davidsonas 494 1 6 17      Did you specify the foreign key when defining the relationship between your models? –  dhofstet Sep 9 '13 at 12:00 1   I'm a bit confused, the name of your Model is "Model" or you're trying to give an example? Update with the exact code you are trying, the name of your table and model and the exact error. –  user221931 Sep 9 '13 at 12:05      and please provide the SQL query that it's generating –  Dave Sep 9 '13 at 13:21      Yes, the model name is just an example –  Tadas Davidsonas Sep 10 '13 at 5:32

 | 

1 Answers
1

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.


answered Sep 9 '13 at 14:04 Nik Chankov 5,762 1 13 28

 | 

------splitte line----------------------------
Related