cakephpcakephp-modelcakephp-2.3mysql-error-1054

Column not found, retrieving data associated model


I've got the following find() function

$this->User->find('all',array(
    'conditions' => array('User.id' => $this->Auth->user('id')),
    'fields' => array('User.id','UserRole.id')
));

And the following associations are defined

// UserRole.php
class UserRole extends AppModel {
    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'user_id'
        )
    );
}

// User.php
class User extends AppModel {
    public $hasMany = array(
        'UserRole' => array(
            'className' => 'UserRole',
            'foreignKey' => 'user_id',
            'dependent' => false,
        )
    );
}

And In App model recursive is set to -1

public $recursive = -1;

The database tables are the following:

CREATE TABLE IF NOT EXISTS `user_roles` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `event_id` int(10) unsigned NOT NULL,
  `role_id` int(10) unsigned NOT NULL,
  `user_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`)

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `first_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `last_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `email` (`email`)

But I get the vollowing error

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UserRole.id' in 'field list'
SQL Query: SELECT `User`.`id`, `UserRole`.`id` FROM `atlanta`.`users` AS `User` WHERE `User`.`id` = 5

I get that cake can't find the UserRole.id, but what did I do wrong?


Solution

  • Either you use some behavior like Containable and your find() will look like this

    $this->User->find('all',array(
        'conditions' => array('User.id' => $this->Auth->user('id')),
        'contain' => array(
            'UserRole' => array(
                'fields'=>array('id')
            )
        ),
        'fields' => array('id')
    ));
    

    OR you set recursive to 1

    $this->User->find('all',array(
        'conditions' => array('User.id' => $this->Auth->user('id')),
        'fields' => array('User.id'), // UPDATE: unfortunately you cant specify associated models fields without behavior
        'recursive' => 1
    ));
    

    The thing is that when recursive is set to -1 or 0 it does not fetch associated models unless some behavior takes care of that for e.g. Containable or Linkable.