好的,所以对于我在 Cakephp 2.2.3 中的项目,我设置了我的数据库和控制器并烘焙了所有内容。我仔细检查了所有内容,并且一切正常(添加、编辑、删除)。我无法工作的一件事是保存到users
表和表之间的中间websites
表。中间表是user_websites
。该user_websites
表只有 3 个字段:id
、user_id
和website_id
。
当我以注册用户身份登录并进入网站添加页面时,我可以毫无问题地添加网站,但它只保存到websites
表格中,表格中没有任何内容user_websites
。摆弄 add 函数中的WebsitesController
我可以让它保存website_id
在user_websites
表中,但同样,对于user_id
. 显然,我需要发生的是,当添加一个新网站时,它应该将该记录保存到websites
表中,并user_websites
使用当前登录用户的 ID 和website_id
刚刚保存的 ID 将记录添加到表中。任何帮助,将不胜感激。谢谢!
这是我的代码:
用户模型
public $hasMany = array(
'UserWebsite' => array(
'className' => 'UserWebsite',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
网站模型
public $hasMany = array(
'UserWebsite' => array(
'className' => 'UserWebsite',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
public $hasAndBelongsToMany = array(
'User' => array(
'className' => 'User',
'joinTable' => 'users_websites',
'foreignKey' => 'website_id',
'associationForeignKey' => 'user_id',
'unique' => 'keepExisting',
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
用户网站模型
public $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
),
'Website' => array(
'className' => 'Website',
'foreignKey' => 'website_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
网站控制器
public function add() {
if ($this->request->is('post')) {
$this->Website->create();
if ($this->Website->UserWebsite->saveAll($this->request->data, array('deep' => true))) {
$log = $this->Website->getDataSource()->getLog(false, false);
debug($log);
$this->Session->setFlash(__('The website has been saved'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The website could not be saved. Please, try again.'));
}
}
}