尝试属于用户(用户有许多尝试)。
在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');
(这看起来有点奇怪,因为我在这个查询的构造之间剥离了很多分散注意力的逻辑。大多数这些条件是根据用户输入动态构建的。)
当我遗漏$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
为什么Attempt模型由于与用户的hasMany关系而自动被包含?
答案 0 :(得分:0)
我认为你的hasMany关联中有一个拼写错误 - className有一个大写N.
我也会尝试测试$this->User->recursive = 2; $this->User->find('first');
,只是为了看看它返回了什么。如果结果不包括Attempt,我会假设您设置模型关系的方式有问题。
答案 1 :(得分:0)
我在这里看不到问题。事实上,今天发布的other question不是答案吗?
但是hasMany和hasAndBelongsToMany不是这种情况 关联。这是强迫联接来救援的地方。您 只需要定义必要的连接来组合表并获得 您的查询所需的结果。
所以,根据我的理解,你在谈论hasMany
时必须强制加入关系,对吧?这就是你在使用$joins
数组时所做的事情。由于User hasMany Attempt
,您必须强制加入。现在,如果您从Attempt
的角度进行分页,则可能不需要这样做。如果您执行$this->Paginator->paginate('Attempt');
(更改必要的关系和条件),则无需手动加入用户表来获取数据。
所以,如果Attempt
本身没有加入(根据文档所说),则订单条件会产生问题,因为在另一个查询和表格中检索到Attempt
数据引用在第一个查询中丢失。解决方案:进行连接,蛋糕的行为符合预期。
答案 2 :(得分:0)
试一试<\ n>
$this->User->bindModel(array('hasMany' => array(
'FollowUp' => array('className' => 'FollowUp', 'foreignKey' => 'publisher_id',
'fields' => array('amount'),
),
'SchoolFollow' => array('className' => 'SchoolFollow', 'foreignKey' => 'publisher_id',
'fields' => array('amount'),
),
'TravelerFollow' => array('className' => 'TravelerFollow', 'foreignKey' => 'publisher_id',
'fields' => array('amount'),
),
$mdl . 'Cashback' => array('className' => $mdl . 'Cashback', 'foreignKey' => 'publisher_id',
'fields' => array('admin_comission_amount'),
'conditions' => array('status' => 'done')
),
)));