ここではCakePHP2.x Modelの簡単な解説をしていきます。

サンプルソースのsql文は仕事で使ったものをそのまま使用しているだけなので、
ご了承お願いします。
サンプルソース
<?php
class Article extends AppModel {
public $useTable = 'dtb_article';
public $primaryKey = 'id';
/**
* $this->query
* @param type $limit
*/
public function getQuery($limit) {
$sql = "SELECT id, name "
. " FROM dtb_article AS ar "
. " LEFT JOIN dtb_news AS ne ON ar.id = ne.id "
. " WHERE ar.delflg = 0 "
. " GROUP BY ar.id "
. " ORDER BY MAX(regi_date) DESC "
. " LIMIT {$limit}";
return $this->query($sql);
}
/**
* 1レコード
* @param type $id
*/
public function getRow($id) {
$sql = "SELECT * "
. " FROM dtb_article "
. " WHERE id = {$id} ";
list($result) = $this->query($sql);
return $result['dtb_article'];
}
/**
* 1列
*/
public function getName() {
$sql = "SELECT name "
. " FROM dtb_article ";
$data = $this->query($sql);
$result = Set::extract('/dtb_article/name', $data);
return $result;
}
/**
* インデックス=>値
*/
public function getList() {
$options = array(
"fields" => array(
"id",
"name",
)
);
$this->find("list", $options);
}
}
解説
public $useTable = ‘dtb_article’; (4行目)
class名が規約に沿わない場合テーブル名の指定してください。
public $primaryKey = ‘id’; (5行目)
カラム名primaryKeyがidではない場合のみ指定してください。
idなら省略可です。
$this->query (11~20行目)
sql文でデータを取得したいときに使用してください。
Set::extract(‘/dtb_article/name’, $data); (37~43行目)
配列のソートです。
Set::extract(/テーブル名/カラム名,query結果)で指定するとnameの1次元配列で返してくれます。
$this->find(“list”, $options); (48~56行目)
id => nameの配列で返します。
$this->find(“list”)とすると
テーブルのカラム名id => nameがデフォルトで選択されます。
とりあえずデータの取得でよく使う方法をまとめてみました。
