cakephp 1.3 テーブル連結

自分用メモ

cakephp 1.3 テーブルの連結

■テーブルを連結 $hasOne してデータ取得するまで
------------------------------------------------------------
データベースにmembersテーブルと連結するProfilesテーブルを作成
------------------------------------------------------------
mysql>
CREATE TABLE profiles (id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY, member_id INT UNSIGNED UNIQUE, freetext VARCHAR(200));
INSERT INTO profiles (id, member_id, freetext) VALUES (0,'4','FREEEEEEEEE'); # サンプルデータ
------------------------------------------------------------
※テーブル名に複数形sがついていることに注意
※profiles テーブルの id カラムと連結させるのは members テーブルのidと指定
------------------------------------------------------------
モデル
------------------------------------------------------------
$ vi app/models/member.php
------------------------------------------------------------
class Member extends AppModel
{
 var $name = 'Member';
 var $hasOne = array(
  'Profile' =>
  array(
   'className' => 'Profile',
   'conditions' => '',
   'order' => '',
   'dependent' => true,
   'foreignKey' => 'member_id'
  )
 );
}
------------------------------------------------------------
コントローラ
------------------------------------------------------------
$ vi app/controllers/member_controller.php
------------------------------------------------------------
<?php
class MemberController extends AppController
{
function index()
{
 $results = $this->Member->find('first', array('conditions'=>array('Member.id'=>4)));
 $this->set('results', $results);
 //var_dump($results);
 }
}
------------------------------------------------------------
ビュー
------------------------------------------------------------
$ vi app/views/member/index.ctp
------------------------------------------------------------
<li><?php echo $results['Member']['id']; ?></li>
<li><?php echo $results['Member']['name']; ?></li>
<li><?php echo $results['Profile']['id']; ?></li>
<li><?php echo $results['Profile']['member_id']; ?></li>
<li><?php echo $results['Profile']['freetext']; ?></li>
------------------------------------------------------------