WebプログラミングV

 目次へ 前へ 次へ

2014/1/7 久米

VCakePHP

3. 検索 

本節で初めて出てくるメソッド とプロパティ

クラス メソッド プロパティ 備考
C AppController set    
M AppModel find
query
   
V View      
     

3.1 全検索

  ファイル コード例 備考
C app>Controller>
NekoYohinsController.php
<?php

class NekoYohinsController extends AppController {
    
	public function index() {
		$datas = $this->NekoYohin->find('all');
		$this->set('ds',$datas);
	}
    

}

 
M app>Model>
NekoYohin.php
無ければデフォルトでオブジェクト生成してくれるので。今回は不要  
V
その1
app>View>
NekoYohins>index.ctp
<h1>猫用品</h1>
<pre><?php print_r($ds); ?></pre>
 
V
その2
app>View>
NekoYohins>index.ctp
<h1>猫用品</h1>
<table>
<?php foreach ($ds as $d): ?>
<tr>
<td><?php echo $d['NekoYohin']['id']; ?></td>
<td><?php echo $d['NekoYohin']['name']; ?></td>
<td><?php echo $d['NekoYohin']['kind']; ?></td>
<td><?php echo $d['NekoYohin']['price']; ?></td>
</tr>
<?php endforeach; ?>
</table>
 
  アクセス http://localhost/web3cake/neko_yohins/  


参考)Viewはコンテンツのみ定義、レイアウトはhtml全体を定義

 

演習2

  1. 演習1で作った××の××cakeアプリを改造して、全検索してみよ。

 

3.2 絞り込み検索

  ファイル コード例 備考
C app>Controller>
NekoYohinsController.php
<?php

class NekoYohinsController extends AppController {
    
	public function index() {
		$datas = $this->NekoYohin->find('all');
		$this->set('ds',$datas);
	}
    
	public function search_kind(){	
		$datas = $this->NekoYohin->searchKind("食べ物", 1000, 500);
		$this->set('ds', $datas);
  }

}
 
M app>Model>
NekoYohin.php
<?php

class NekoYohin extends AppModel{

    public function searchKind($kind, $p_miman, $p_ijo){
		$sql = " SELECT * FROM neko_yohins as NekoYohin "
        		."WHERE kind=? AND price<? AND price>=?";
		$yohins = $this->query($sql,array($kind, $p_miman, $p_ijo));
		return $yohins;
    }
}
【query使用時の注意事項】
SQL文で
テーブル名 as モデル名
としておく。
そうすると検索結果に
モデル名の連想配列が
使われるため
viewが作りやすい
$d['NekoYohin']['id']
V
その1
app>View>
NekoYohins>search_kind.ctp
<h1>猫用品</h1>
<pre><?php print_r($ds); ?></pre>
 
V
その2
app>View>
NekoYohins>search_kind.ctp
<h1>猫用品</h1>
<table>
<?php foreach ($ds as $d): ?>
<tr>
<td><?php echo $d['NekoYohin']['id']; ?></td>
<td><?php echo $d['NekoYohin']['name']; ?></td>
<td><?php echo $d['NekoYohin']['kind']; ?></td>
<td><?php echo $d['NekoYohin']['price']; ?></td>
</tr>
<?php endforeach; ?>
</table>
 
  アクセス http://localhost/web3cake/neko_yohins/search_kind  

 

演習3

  1. 演習1で作った××の××cakeアプリを改造して、絞り込み検索してみよ。