假设我有 3 个模型:用户、区域、国家/地区。
User belongsTo Region
Region belongsTo Country
这些模型中的每一个都使用 Containable 行为。我正在尝试查找来自代码为“US”的国家/地区的用户。这就是我正在尝试的:
$users = $this->User->find('all', array(
'conditions' => array('Country.code' => 'US'),
'contain' => array('Region.Country'),
));
CakePHP 将其分为 2 个查询:
- 首先,它选择所有代码为“US”的国家/地区的 ID。
- 然后,它使用这些 ID 来选择加入区域的所有用户,其中
region.country_id
位于先前检索到的国家/地区 ID 列表中。
结果,我的应用程序中出现了 SQL 错误,因为我的 conditions
数组包含对 Country.code 的引用,并且 Cake 构建的第二个查询没有加入国家/地区。
我看到的最好的 Cake 解决方案是构建一个子查询,如 Complex 中所述查找手册的条件部分。然而,这看起来非常复杂,而且比我想要实现的更像是一种黑客行为。有没有一种我忽略的更简单的方法?
Let's say I have 3 models: User, Region, Country.
User belongsTo Region
Region belongsTo Country
Each of these models is using the Containable behavior. I'm attempting to find users from the country with code 'US'. Here's what I'm attempting:
$users = $this->User->find('all', array(
'conditions' => array('Country.code' => 'US'),
'contain' => array('Region.Country'),
));
CakePHP is separating this into 2 queries:
- First, it is SELECTing the ID's for all countries with code 'US'.
- Then it is using those ID's to SELECT all users JOINing regions where
region.country_id
is in that list of country ID's previously retrieved.
As a result, I end up with SQL errors in my app since my conditions
array contains a reference to Country.code, and the second query that Cake builds doesn't JOIN countries.
The best Cake solution I see is to build a sub-query as described in the Complex Find Conditions portion of the manual. However, this seems very convoluted, and is more of a hack than I would like to implement. Is there an easier way that I'm overlooking?
发布评论
评论(2)
Nate Abele(CakePHP 的前首席开发人员)写了一篇关于执行 临时加入可能会有所帮助。
Nate Abele (former lead dev of CakePHP) wrote an article about doing ad hoc joins which might help.
将条件也放入容器中。例如:
请参阅 Containable 手册中的倒数第二个示例
Put the conditions in the contain as well. E.g:
See the second-to-last example in the Containable manual