0

我有以下 find() 函数

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

并定义了以下关联

// 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,
        )
    );
}

并且 In App 模型递归设置为 -1

public $recursive = -1;

数据库表如下:

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`)

但我得到了错误

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

我得到那个蛋糕找不到 UserRole.id,但我做错了什么?

4

1 回答 1

0

要么你使用像Containable这样的行为,你的 find() 看起来像这样

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

或者你将递归设置为 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
));

问题是,当 recursive 设置为 -1 或 0 时,它不会获取关联的模型,除非某些行为负责处理,例如 Containable 或 Linkable。

于 2013-05-21T11:33:02.540 回答