我有以下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,
)
);
}
并且在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,但我做错了什么?
答案 0 :(得分: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时,它不会获取关联模型,除非某些行为处理了例如包含或可链接。