跨多个模型构建条件语句 (CakePHP 1.2.5)

发布于 2024-08-08 22:17:24 字数 834 浏览 11 评论 0 原文

假设我有 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 个查询:

  1. 首先,它选择所有代码为“US”的国家/地区的 ID。
  2. 然后,它使用这些 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:

  1. First, it is SELECTing the ID's for all countries with code 'US'.
  2. 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

为人所爱 2024-08-15 22:17:24

Nate Abele(CakePHP 的前首席开发人员)写了一篇关于执行 临时加入可能会有所帮助。

Nate Abele (former lead dev of CakePHP) wrote an article about doing ad hoc joins which might help.

能怎样 2024-08-15 22:17:24

将条件也放入容器中。例如:

$users = $this->User->find('all', array('contain' => array(
    'Region' => array(
        'Country' => array(
            'conditions' => array('Country.code' => 'US'),
        ),
    ),
)));

请参阅 Containable 手册中的倒数第二个示例

Put the conditions in the contain as well. E.g:

$users = $this->User->find('all', array('contain' => array(
    'Region' => array(
        'Country' => array(
            'conditions' => array('Country.code' => 'US'),
        ),
    ),
)));

See the second-to-last example in the Containable manual

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文