我有两个表和一个连接表。我尝试使用$ hasAndBelongsToMany,但它没有用,所以我为连接表创建了一个模型并使用。
User hasMany Membership
Membership belongsTo User, Club
Club hasMany Membership.
我有一个可以保存到两个表格的表单。
function dashboard_add(){
$user = $this->Session->read('User');
$register = false;
if (!empty($this->data)) {
if($this->Club->saveAll($this->data)){
$this->Session->setFlash(__('You have registered your club. You will be contacted soon!', true), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('There was a problem with your registration. Please, try again.', true), 'default', array('class' => 'warning'));
}
}
if (empty($this->data)) {
$this->data = $this->User->read(null, $user['User']['id']);
}
$this->set(compact('register'));
}
用户模型
var $hasMany = array(
'Membership' => array(
'className' => 'Membership',
'foreignKey' => 'user_id'
)
);
会员模型
var $belongsTo = array('User','Membership');
分会模特
var $hasMany = array(
'Membership' => array(
'className' => 'Membership',
'foreignKey' => 'club_id'
),
'Upload' => array(
'className' => 'Upload',
'foreignKey' => 'club_id'
)
);
我没有收到任何错误。俱乐部表填充,但成员资格和用户表不插入/更新。
更新:调试($ this-> Club-> save($ this-> data));
Array
(
[User] => Array
(
[id] => 1
[first_name] => this
[last_name] => that
[company_name] => other
[city] => this
[state] => that
[zip] => other
[telephone] => that
[email_address] => this
)
[Club] => Array
(
[address] => fvdfvx
[title] => xcvxcv
[category] => xcvxcv
[modified] => 2012-05-03 06:31:12
)
)
答案 0 :(得分:0)
我认为你正在使用cakePHP 1.3.x.请参阅文档以了解cake如何同时保存许多模型,您需要生成一个包含所有模型的数组以保存..例如:
Array
(
[Article] => Array
(
[title] => My first article
)
[Comment] => Array
(
[0] => Array
(
[comment] => Comment 1
[user_id] => 1
)
[1] => Array
(
[comment] => Comment 2
[user_id] => 2
)
)
)
http://book.cakephp.org/1.3/view/1031/Saving-Your-Data
显然在你的$ this->数据中你只有一个简单的数组[User]。而不是像示例中那样保存多个数组。
我希望我有所帮助。 问候。