2013-05-21 32 views
0

()函數列沒有發現,檢索我有以下查找數據關聯的模型

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

並在應用模型遞歸設置爲 - 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`) 

但我得到的vollowing錯誤

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

要麼你使用像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 
)); 

的事情是,當遞歸設置爲 - 1或0它不會獲取關聯的模型,除非某些行爲可以處理例如可容納或可鏈接。

+0

遞歸選項不起作用,但可容納的選項沒有!謝謝! –

+0

哦,是的,我忘記了你不能單獨指定遞歸關聯模型的字段,你需要一個行爲來做到這一點。無論如何,不​​客氣。 – 2013-05-21 11:41:01

相關問題