【问题标题】:matching associations and no associated record cakephp 3匹配的关联和没有关联的记录 cakephp 3
【发布时间】:2016-02-05 11:29:47
【问题描述】:

我有一个Price 的关联属于Season

我正在尝试查询当季过去时与特定日期范围匹配的所有价格以及没有的价格 (Prices.season_id=0)

这是我所拥有的:

// build the query
$query = $this->Prices->find()
  ->where(['product_id'=>$q['product_id']])
  ->contain(['Seasons']);

if(!empty($to_date) && !empty($from_date)) {
  $query->matching('Seasons', function ($q) {
    return $q->where([
      'from_date <= ' => $to_date,
      'to_date >= ' => $from_date
    ]);
  });
}

但是,这只会返回与季节明确关联的价格。如何让它也返回 Prices.season_id=0?

【问题讨论】:

    标签: orm associations matching cakephp-3.1


    【解决方案1】:

    $query-&gt;matching() 调用在内部创建一个 INNER JOIN 并将回调函数的 where 语句放入连接的 ON 子句中。要检索没有关联的项目,您需要LEFT JOIN。所以你的 coden-p 看起来像这样:

    if(!empty($to_date) && !empty($from_date)) {
        $query->leftJoinWith('Seasons', function ($q){return $q;});
        $query->where([[
            'or' => [
                'Season.id IS NULL',
                [
                    'from_date <= ' => $to_date,
                    'to_date >= ' => $from_date,
                ],
            ],
        ]]);
    }
    

    所以我们创建一个普通的INNER JOIN 并将条件放在查询的普通(最外层)where 子句中。

    双精度数组用于消除可能具有or 连接的其他条件。

    我自己偶然发现了 column IS NULL 而不是 'column' =&gt; null 语法。

    PS:这适用于所有协会。对于hasManybelongsToMany,您必须将结果与$query-&gt;group('Prices.id') 分组

    【讨论】:

      猜你喜欢
      • 2016-08-12
      • 1970-01-01
      • 2011-10-23
      • 2011-07-16
      • 1970-01-01
      • 2013-09-24
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多