2
votes

I am learning CakePHP. There, I am stuck with following problem:

I have a table called comments with fields comment_id, comment_title, comment_text, comment_date & user_id. Also I have my users table with fields user_id, user_name, user_email, created_date.

Then in my User model I am trying to create a hasMany relationship like :

var $hasMany = array(
    'Comment' => array(
    'className' => 'Comment',
    'foreignKey' => 'user_id'
    ), );

But this giving me an error

1054 Unknown column 'User.id' in 'field list'

I know this is because I don't have an id column in my users table instead I have user_id

Now, my question is : is there a way to fix this without renaming the user_id field of user table? As this will require change in every existing code where I have used user_id ?

3
Why are you not simply following the conventions and name the primary keys "id" in your tables? This will save you a good amount of work.floriank

3 Answers

2
votes

Set in your User model:

public $primaryKey = 'user_id';

If you need create some relationship and models, controller, views.. You can use Bake shell, see: http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html

1
votes

To avoid this kind of errors use foreign key constraints in database. Cakephp automatically add associations between tables.

-1
votes
public $hasMany = array(
    'Comment' => array(
        'className' => 'Comment',
        'foreignKey' => 'user_id',
        'conditions' => array('Comment.user_id' => 'User.user_id'),
        'dependent' => true
    )
);