我遵循了 CakePHP 的基本身份验证教程。如果我添加一个用户,我不能用他登录。带有输入的视图应该没问题。 背景:用户 HASANDBELONGSTOMANY带有连接表的播客。
控制器/用户控制器.php
public function add() {
if ($this->request->is('post')) {
$this->User->create();
if ($this->User->saveAssociated($this->request->data)) { //saveAssociatied() is described below
$this->redirect(array('action' => 'index'));
}
}
$podcasts = $this->User->Podcast->find('list');
$this->set(compact('podcasts'));
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
$this->redirect($this->Auth->redirect());
}
}
}
模型/用户.php
public $hasAndBelongsToMany = array(
'Podcast' => array(
'className' => 'Podcast',
'joinTable' => 'podcasts_users',
'foreignKey' => 'user_id',
'associationForeignKey' => 'podcast_id',
'unique' => false,
)
);
//password encryption
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
AppModel.php(根据this)
class AppModel extends Model {
public function saveAssociated($data = null, $options = array()) {
foreach ($data as $alias => $modelData) {
if (!empty($this->hasAndBelongsToMany[$alias])) {
$habtm = array();
$Model = ClassRegistry::init($this->hasAndBelongsToMany[$alias]['className']);
foreach ($modelData as $modelDatum) {
if (empty($modelDatum['id'])) {
$Model->create();
}
$Model->save($modelDatum);
$habtm[] = empty($modelDatum['id']) ? $Model->getInsertID() : $modelDatum['id'];
}
$data[$alias] = array($alias => $habtm);
}
}
return parent::saveAssociated($data, $options);
}
}