我在Pagination和蛋糕排序方面遇到了问题。我可以使用第一个表进行排序,但如果我尝试使用第二个表进行排序则不能。
我有以下表格(以及相应的型号): 用户:id,用户名 user_companies:id,user_id,company_id 公司:id,name
所以这很好用:
$this->User->find("all");
Pagiation工作正常:
$this->Paginator->settings = array('sort'=>'User.username');
$this->Paginator->paginate();
但如果我尝试按公司名称排序,我会收到错误:
$this->Paginator->settings = array('sort'=>'Company.name');
$this->Paginator->paginate();
错误:SQLSTATE [42S22]:找不到列:1054未知列 'order子句'中的'Company.name'SQL查询:SELECT
User
。id
,User
。User
。username
,User
。password
,User
。role
,User
。created
,User
。modified
FROMcakeblog
。users
ASUser
WHERE 1 = 1 ORDER BYCompany
。name
asc LIMIT 20
为什么这不起作用?
我的用户模型HABTM如下所示:
public $hasAndBelongsToMany = array(
'Company'=>array(
'with'=>'UserCompanies'
)
);
和公司:
public $hasAndBelongsToMany = array(
'User' => array(
'with' => 'UserCompanies',
)
);
没有排序的默认查询是:(是,因为tehre实际上是两个查询):
SELECT `User`.`id`, `User`.`email`, `User`.`username`, `User`.`password`, `User`.`role`, `User`.`created`, `User`.`modified` FROM `cakeblog`.`users` AS `User` WHERE 1 = 1 LIMIT 20
查询2:
SELECT `Company`.`id`, `Company`.`name`, `CompaniesUser`.`id`, `CompaniesUser`.`user_id`, `CompaniesUser`.`company_id` FROM `cakeblog`.`companies` AS `Company` JOIN `cakeblog`.`companies_users` AS `CompaniesUser` ON (`CompaniesUser`.`user_id` IN (14, 16, 17) AND `CompaniesUser`.`company_id` = `Company`.`id`)
答案 0 :(得分:0)
我最终创建了两个连接。现在它按预期工作,我可以使用Company.name或任何其他字段进行排序:
$joins = array();
$joins[] = array(
'table'=>'companies_users',
'alias'=>'CompanyUser',
'type'=>'LEFT',
'conditions'=>array(
'CompanyUser.user_id = User.id'
)
);
$joins[] = array(
'table'=>'companies',
'alias'=>'Company',
'type'=>'LEFT',
'conditions'=>array(
'CompanyUser.company_id = Company.id')
);
$this->Paginator->settings = array('sort'=>'Company.name', 'joins'=>$joins);
$x = $this->paginate();
debug($x);