findAllByAreaGroupId を使って、検索して取得するパターン
■Model
find 系を使うので特に変更なし
■Controller
/Store?group=10 でアクセスできるようにコントローラを作成
in Controller/StoreController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class StoreController extends AppController { public function index() { $id = null; $group = null; if (isset( $this ->params[ 'url' ][ 'id' ])) $id = $this ->params[ 'url' ][ 'id' ]; if (isset( $this ->params[ 'url' ][ 'group' ])) $group = $this ->params[ 'url' ][ 'group' ]; if ( $id != null ) { $this ->set( 'Store' , $this ->Store->findAllById( $id )); } else if ( $group != null ) { $this ->set( 'Store' , $this ->Store->findAllByAreagroupid( $group )); } else { $this ->set( 'Store' , $this ->Store->find( 'all' , array ( 'limit' => '100' ))); } } } |
パラメータで取得するので、$this->params[‘url’][‘group’] を使う。isset チェックを忘れずに。
PK ではないので、数百行返される可能性もあるので、limit をつけたほうがベターかも。
findAllByAreagroupid のところは、findAllByAreaGroupId のように書きたいところだが、このように書くと「area_group_id」のように展開されてしまうので「Areagroupid」のようにすべて小文字で書く。
limit を使おうとすると、conditions を指定しないとだめで、
1 2 3 4 5 | $this ->set( 'Store' , $this ->Store->find( 'all' , array ( 'limit' => 10, 'conditions' => array ( 'AreaGroupId' => $group )))); |
な風に長くなる。なんらかのヘルパー関数が必要かも…って慣れれば大丈夫?
■View
戻り値は配列になるので、foreach のところはそのままで。
■結果
指定したグループの最初の10件が表示されている(conditions を使ったパターン)。