嘗試屬於用戶(用戶有很多嘗試)。CakePHP:hasMany association not recognized
在user.php的(模型)
public $hasMany = array (
'Attempt' => array(
'className' => 'Attempt',
'order' => 'modified DESC'
),
);
在Attempt.php(模型)
public $belongsTo = array (
'Test' => array ('className' => 'Test', 'foreignKey'=>'test_id', 'order' => 'Test.created DESC'),
'User' => array ('className' => 'User', 'order' => 'User.created DESC')
);
在控制器中,我們構建此查詢...
$joins = array(
array(
'table'=>'attempts',
'alias'=>'Attempt',
'type'=>'LEFT',
'conditions'=>array("Attempt.user_id = User.id AND Attempt.test_id != {$practice_test_id}")
)
);
$conditions[] = array('Resume.has_file = 1');
$search_options = array('conditions'=>$conditions,
//'joins' => $joins, //<--I'M FORCED TO USER THIS TO GET THIS TO WORK
'contain' => array('Resume', 'Attempt', 'Tag'),
'order' => array('Attempt.score'=> 'DESC'),
'group' => 'User.id'
);
$paginator_settings = $search_options;
$paginator_settings['limit'] = 25;
$this->Paginator->settings = $paginator_settings;
$resume_display_array = $this->Paginator->paginate('User');
(這裏看起來有點奇怪,因爲我在這個查詢的構造之間剝去了很多分散注意力的邏輯,其中大多數c onditions是基於用戶輸入動態構建的。)
當我忽略了$search_options['joins]
這不起作用。我得到以下錯誤:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Attempt.score' in 'order clause'
的SQL轉儲看起來是這樣的:
SELECT `User`.`id`
FROM `users` AS `User`
LEFT JOIN `resumes` AS `Resume` ON (`Resume`.`user_id` = `User`.`id`)
WHERE `User`.`id` IN (
SELECT `User1`.`id` FROM `users` AS User1
LEFT JOIN `tags_users` AS TagUser ON (`User1`.`id`= `TagUser`.`user_id`)
LEFT JOIN `tags` AS Tag ON (`TagUser`.`tag_id`= `Tag`.`id`)
WHERE `Tag`.`id` = (2)) AND `Resume`.`has_file` = 1 GROUP BY `User`.`id`
ORDER BY `Attempt`.`score` DESC
LIMIT 25
爲什麼沒有得到自動包含在嘗試模型由於與用戶的關係的hasMany?
如果您複製並粘貼到你的數據庫是SQL它返回的東西? Attempts表中是否存在「分數」列? –