cakephp - Automatically adding of foreign key (userid of logged user) -
i newbie in programming cakephp, have implemented simple user-game application. there "hasmany" relation between users , game. game created 1 user. therefore there field in model of game, named "user_id". using auth component , possible user can login system. now, want user can add games model, user_id should added automatically( acessing session data). how can achieve ?
stannis :)
now, want user can add games model, user_id should added automatically( acessing session data). how can achieve ?
first, highly recommend official blog tutorial, because cover questions you.
in controller:
public function add() { if ($this->request->is('post') { $this->request->data['game']['user_id'] = $this->auth->user('id'); $this->game->save($this->request->data); } }
but can , should done better moving logic model, remember: fat models, skinny controllers. here broken down , short example:
// controller public function add() { if ($this->request->is('post') { $this->game->add($this->auth->user('id'), $this->request->data); } } // model public function add($userid, $postdata) { $postdata[$this->alias]['user_id'] = $userid; return $this->save($this->request->data); } }
usually don't want access session directly in model because requires use static or singleton call auth component or session object, want avoid as can.
Comments
Post a Comment