[CakePHP] 指定したグループを検索して表示する

findAllByAreaGroupId を使って、検索して取得するパターン

■Model

find 系を使うので特に変更なし

■Controller

/Store?group=10 でアクセスできるようにコントローラを作成

in Controller/StoreController.php

[code lang=”php”]
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’)));
}
}
}
[/code]

パラメータで取得するので、$this->params[‘url’][‘group’] を使う。isset チェックを忘れずに。
PK ではないので、数百行返される可能性もあるので、limit をつけたほうがベターかも。

findAllByAreagroupid のところは、findAllByAreaGroupId のように書きたいところだが、このように書くと「area_group_id」のように展開されてしまうので「Areagroupid」のようにすべて小文字で書く。

limit を使おうとすると、conditions を指定しないとだめで、

[code lang=”php”]
$this->set(‘Store’,
$this->Store->find(‘all’,
array(
‘limit’ => 10,
‘conditions’ => array(‘AreaGroupId’=>$group))));
[/code]

な風に長くなる。なんらかのヘルパー関数が必要かも…って慣れれば大丈夫?

■View

戻り値は配列になるので、foreach のところはそのままで。

■結果

指定したグループの最初の10件が表示されている(conditions を使ったパターン)。

カテゴリー: CakePHP パーマリンク