「cakephp」カテゴリーアーカイブ

バインド アソシエーション bindModel

常に連結させたくないテーブルがあり、場合によっては連結させてデータを取りたいときも出てくる
そんなときに「メソッドが呼び出されたタイミングで連結を行う」これをバインドという
[php]
public function adduser(){
$belongsTo = array(
‘User’ => array(
‘className’ => ‘User’,
‘foreignKey’ => ‘user_id’
));
$this->bindModel(array("belongsTo" => $belongsTo));
$data = $this->find(‘all’);
return $data;
}
[/php]

参考 : http://offsidenow.phpapps.jp/archives/1447

ログインしているユーザーIDで保存する

これを保存する際に追加
[php]$this->request->data[‘Post’][‘user_id’] = $this->Auth->user(‘id’); [/php]

[php]
public function add() {
if ($this->request->is(‘post’)) {
$this->Post->create();
$this->request->data[‘Post’][‘user_id’] = $this->Auth->user(‘id’); //postテーブルのuser_idにログインしているユーザー情報を保存するよ
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__(‘The post has been saved.’));
return $this->redirect(array(‘action’ => ‘index’));
} else {
$this->Session->setFlash(__(‘The post could not be saved. Please, try again.’));
}
}
$users = $this->Post->User->find(‘list’);
$this->set(compact(‘users’,’options’));

}
[/php]

参考:http://offsidenow.phpapps.jp/archives/1447