cakephpでHABTMなアソシエーションが思うように動作しないので単純化テストする その4
HABTMフィルタは2回に分けて検索すると簡単
- コメントで教えていただいた↓を参考に実験
- http://www.exgear.jp/blog/2009/06/cakephp-habtm%E3%83%A2%E3%83%87%E3%83%AB%E3%81%AE%E6%A4%9C%E7%B4%A2/
- HABTMで関連付けされたテーブルを検索条件に加えたい場合、一回のfindメソッドで取得しようとすると、joinの設定やグループ化で面倒な実装が必要になってきます。
- とのことなので、一発でやることもできるらしいけど、それはまたの機会に
- HABTMで関連付けされたテーブルを検索条件に加えたい場合、一回のfindメソッドで取得しようとすると、joinの設定やグループ化で面倒な実装が必要になってきます。
まずCategoriesProduct.category_id' => 1なProductのリストを取得
$dataList = $this->Product->CategoriesProduct->find('list', array( 'fields' => array('CategoriesProduct.product_id'), 'conditions' => array('CategoriesProduct.category_id' => 1))); pr($dataList);
Array ( [3] => 3 [2] => 2 [1] => 1 [7] => 7 [9] => 9 [10] => 10 [11] => 11 [12] => 12 [13] => 13 [14] => 14 [15] => 15 [16] => 16 [17] => 17 )
そのProductリストに対してpaginate()検索する
$this->paginate = array( 'limit' => 10, 'order' => 'Product.id'); $products = $this->paginate('Product', array( 'Product.hidden' => 0, 'Product.id' => $dataList));
Array ( [0] => Array ( [Product] => Array ( [id] => 1 [name] => りんご [hidden] => 0 ) [Category] => Array ( [0] => Array ( [id] => 1 [name] => 果物 ) ) ) ...
- 期待通りのデータをページングで表示できた