好的,我的另一个蛋糕问题。
我有一个相当复杂的表结构,其中有很多连接。这是它的要点:
所以,总结一下:
RiskCategory $hasMany Client [Client $belongsTo RiskCategory]
Client $hasMany Account [Account $belongsTo Client]
Account $hasMany Holding [Holding $belongsTo Account]
在我的 RiskCategory
模型中,我想运行一个查询,该查询基本上返回每个 riskCategory id 中的持股总和,按日期分组。还有一些其他条件,但这是我放在一起的条件:
$findParams = array(
'recursive' => 4,
'fields' => array(
'Holding.holding_date',
'SUM(Holding.value) AS risk_category_value'
),
'group' => array('Holding.holding_date'),
'order' => 'Holding.holding_date ASC'
);
$findParams['conditions'] = array(
'Client.active' => true,
'Client.model' => true,
'Client.currency' => 'GBP',
'OR' => array(
'Holding.holding_date' => $this->end_date,
array(
'Holding.holding_date = LAST_DAY(Holding.holding_date)',
'MONTH(Holding.holding_date)' => array(3,6,9,12)
)
)
);
$valuations = $this->Client->Account->Holding->find( 'all', $findParams );
当我运行上面的蛋糕时,出现了一个错误,指出查询中不存在各种字段。创建的原始查询如下:
SELECT `Holding`.`holding_date`,
Sum(`Holding`.`value`) AS risk_category_value
FROM `ips_client_db`.`holdings` AS `Holding`
LEFT JOIN `ips_client_db`.`accounts` AS `Account`
ON ( `Holding`.`account_id` = `Account`.`id` )
LEFT JOIN `ips_client_db`.`sedols` AS `Sedol`
ON ( `Holding`.`sedols_id` = `Sedol`.`id` )
WHERE `client`.`active` = '1'
AND `client`.`model` = '1'
AND `client`.`currency` = 'GBP'
AND ( ( `Holding`.`holding_date` = '2013-10-01' )
OR (( ( `Holding`.`holding_date` = Last_day(
`Holding`.`holding_date`) )
AND ( Month(`Holding`.`holding_date`) IN ( 3, 6, 9, 12 ) ) )
) )
GROUP BY `Holding`.`holding_date`
ORDER BY `Holding`.`holding_date` ASC
看起来好像 cake 没有做所有的连接。它只是将 Account
连接到 Holding
,然后将 Holding
连接到 Sedol
(这是数据库中的另一个连接表,但是这个查询不需要它,所以我从图中省略了它)
为什么连接不正确,如何实现?如果可能的话,我想避免写一个原始语句。
编辑:连接应如下所示:
...
FROM risk_categories
LEFT JOIN ((clients
LEFT JOIN accounts
ON clients.id = accounts.client_id)
LEFT JOIN holdings
ON accounts.id = holdings.account_id)
ON risk_categories.id = clients.risk_category_id
...
最佳答案
CakePHP 不会为深度超过 1 级的关联执行深度连接。这就是为什么在条件中引用 Client
表时出现错误的原因。
对于这些类型的问题,使用 Containable 更容易行为。我通常将此行为添加到我的 AppModel
作为关联的默认处理程序。
Containable 允许您定义关联(仅那些已经定义的)及其字段和条件作为查找操作的一部分。这是通过在查找参数中添加一个新的 contain
键来完成的。下面我猜测您可能需要什么。
$findParams = array(
'fields' => array(
'Holding.holding_date',
'SUM(Holding.value) AS risk_category_value'
),
'conditions'=>array(
'OR' => array(
'Holding.holding_date' => $this->end_date,
array(
'Holding.holding_date = LAST_DAY(Holding.holding_date)',
'MONTH(Holding.holding_date)' => array(3,6,9,12)
)
)
),
'group' => array('Holding.holding_date'),
'order' => 'Holding.holding_date ASC',
'contain'=>array(
'Account'=>array(
'Client'=>array(
'RiskCategory',
'conditions'=>array(
'Client.active' => true,
'Client.model' => true,
'Client.currency' => 'GBP',
)
)
)
)
);
$valuations = $this->Client->Account->Holding->find( 'all', $findParams );
关于php - CakePHP 没有在查找查询中加入正确的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19155658/