Store というテーブルがあるとして、
■Model
テーブル名を複数形にしたくない(既存のテーブル名を変えたくない)ので、$useTable で指定
in Model/Store.php
[code lang=”php”]
class Store extends AppModel
{
var $useTable = ‘Store’; // 対象テーブル名を指定
}
[/code]
find 系の関数だけを使うのであれば、最初は空で ok 。
■Controller
/Store でアクセスできるようにコントローラを作成
in Controller/StoreController.php
[code lang=”php”]
class StoreController extends AppController {
public function index() {
$this->set(‘Store’, $this->Store->find(‘all’,array(‘limit’=>’100’)));
}
}
[/code]
全件検索すると1万行ぐらいあるので、最初の100行で打ち切り。find でリミットを指定できるのだけど、ここは「安全」にコーディングするために、find100 とかいうメソッドでアクセスしたほうがよいかも。
[code lang=”php”]
class StoreController extends AppController {
public function index() {
$this->set(‘Store’, $this->Store->find100());
}
}
[/code]
この場合は、Model/Store.php に find100 メソッドを追加する。
[code lang=”php”]
class Store extends AppModel
{
var $useTable = ‘Store’;
function find100()
{
$sql = <<< HERE
SELECT
ID, AreaGroupID, Name
FROM Store
limit 0,100
HERE;
return $this->query($sql);
}
}
[/code]
こうやって SQL 文を直書きする。
■View
Controller で設定 $this->set(‘Store’,…) したところが使えるので、そのまま foreach でループさせる。
in View/Store/Index.ctp
[code lang=”php”]
store index の表示
<h2>Store list</h2>
<table>
<tr>
<td>id</td>
<td>areagroupid</td>
<td>name</td>
</tr>
<!–
<?php print_r( $Store ); ?>
–>
<?php foreach($Store as $item) : ?>
<tr>
<td><?php echo $item[‘Store’][‘ID’] ?></td>
<td><?php echo $item[‘Store’][‘AreaGroupID’] ?></td>
<td><?php echo $item[‘Store’][‘Name’] ?></td>
</tr>
<?php endforeach ; ?>
[/code]
■結果
先頭の 100 件だけ表示する。
