今、StoresというモデルにたくさんのItemsが紐ついているとします。 Itemsはitemの単価(price)とその消費税(consumption_tax)というカラムを持ってます。
今、Storesの持つItemsの総額がある$total_priceに等しいものについて絞り込みを行いたい時、クエリビルダーを用いると以下のようにかけます。
$subquery = $this->find('all');
$subquery->innerJoin(
[ 'Items' => 'items' ],
[ 'Items.store_id = Stores.id' ]
)->select(['total_price' => $query->func()->sum('Items.price + Items.consumption_tax')])->group('Stores.id')->select(['id' => 'Stores.id']);
$subquery = "({$subquery})";
$query = $this->find('all')->innerJoin(
[ 'TotalPrice' => $subquery ],
[ 'TotalPrice.id = Stores.id']
)->where("TotalPrice.total_price = {$total_price}");
このようにsubqueryに一旦アソシエーションを組んでいるItemsのpriceとconsumption_taxの和をselectしておき、idを軸に元々のtableにinnerJoinしてからwhere句で絞り込むと絞り込めました。


