findAllById を使って、検索して取得するパターンだが、/Store?id=10 ではなくて、/Store/10 のように検索できるようにする。
■Model
find 系を使うので変更なし
■Controller
/Store/10 でアクセスできるようにコントローラを作成…したいのだが、できないので、/Store/index/10 でアクセスする
in Controller/StoreController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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' ))); } } } |
index メソッドの引き数に $id を追加するだけ。
指定されない場合にも対応できるように、デフォルトの値を null にしておく。
/Store/10 でアクセスしようとすると、「10 という名前のメソッドがない」というエラーが出るので、/Store/index/10 でアクセスをする。この場合、/Store/select/10 のようにメソッド名を変えるほうがベターかと。
今回は、Web API なので、/Store?id=10 形式でアクセスするようにしよう。
■View
戻り値は配列になるので、foreach のところはそのままで。
■結果
指定したIDが表示される。