【问题标题】:How to filter containments by associated data?如何按关联数据过滤容器?
【发布时间】:2017-08-24 10:49:57
【问题描述】:

只有当二级关联数据遵守给定条件时,我才想获得关联。

查询可能会更好地解释我尝试做的事情。

$selSite = $this->Sites->get($selSiteId, [
    'contain' => [
        'Agplans.Products' => function ($q) {
            return $q
            ->where([
                'Products.type' => 'hosting',
            ]);
        }
    ]
]);

所以我只希望 agplan 的关联产品符合条件。

但结果是:

'agplans' => [
    (int) 0 => object(App\Model\Entity\Agplan) {

        'id' => (int) 20,
        'product_id' => (int) 4,
        'product' => null,
        ...,

    },
    (int) 1 => object(App\Model\Entity\Agplan) {

        'id' => (int) 21,
        'site_id' => (int) 64,
        'product_id' => (int) 75,
        'product' => object(App\Model\Entity\Product) {

            'id' => (int) 75,
            ...,

        },
        ...,

    }
],

我的问题是用product => null 获取agplan[0]。 这不是我从doc 所理解的。 如何仅使用'product' => object(App\Model\Entity\Product) 获取agplan

【问题讨论】:

  • 对我来说听起来像 stackoverflow.com/questions/26799094/…
  • @ndm 我不认为这是同一个问题。在这里,我不想得到几个关联匹配条件的站点,我只 get 一个特定站点。我只是想在这里过滤掉它的关联。 doc 解释了什么告诉It is also possible to restrict **deeply-nested associations** using the dot notation:。我没有看到我在这里不明白的地方。

标签: cakephp associations filtering query-builder cakephp-3.x


【解决方案1】:

感谢@ndm 指出的,我明白我必须像这样构建我的查询:

$selSite = $this->Sites->get($selSiteId, [
    'contain' => [
        'Agplans.Products',
        'Agplans' => function ($q) {
            return $q
            ->matching('Products', function ($q) {
                return $q
                ->where([
                    'type' => 'hosting',
                ]);
            });
        }
    ]
]);

那样,我只能得到与给定 product 匹配的 agplans。 无论如何,我发现 CakePHP 文档没有明确关于限制关联的包含功能。

【讨论】:

  • 我想这对于那些还不熟悉收容措施的人来说可能有点困惑,所以你可能想report this as an issue,一个关于“深度限制”的小提示嵌套关联”指的是,它不应该与关联数据过滤相混淆,肯定不会受到伤害。
  • @ndm,这是否被视为一个问题?我目前提议在这一点上澄清文档。
  • 嗯,“问题”当然可以根据上下文表示很多不同的东西,我只是想参考 GitHub 票证,它们被称为“问题”。我将来也许应该选择更好的措辞。
  • @ndm 好的,我做到了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-10
  • 2015-01-04
  • 1970-01-01
相关资源
最近更新 更多