2016-02-05 97 views
1

Price屬於關聯Season匹配協會和沒有相關的記錄CakePHP的3

我想查詢的季節過去了,以及任何有沒有匹配特定日期範圍內,所有價格的關聯(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?

回答

0

$query->matching()調用內部創建一個INNER JOIN並將回調函數的where語句放入連接的ON子句中。要檢索沒有關聯的項目,您需要一個LEFT JOIN。所以,你的codesnippet應該是這樣的:

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查詢的子句。

雙數組用於消除可能與其他條件有關的連接。

我自己偶然發現了column IS NULL而不是'column' => null語法。 PS:這適用於所有關聯。對於hasManybelongsToMany,您必須將結果與$query->group('Prices.id')