我搜索了很多,但似乎没有什么似乎与我正在寻找...
我想要做的是使用多个HTML列表一次链接一个记录“用户”与其他多个记录“卡” .
表是:用户(id,name,username)卡(id,user_id)
楷模:
class User extends AppModel {
public $name = 'User';
public $hasMany = array('Card');}
class Card extends AppModel {
public $name = 'Card';
public $belongsTo = array('User');}
用户edit.ctp视图
echo $this->Form->input('id');
echo $this->Form->input('Card', array('multiple'=>true));
我的控制器怎么样?目前它看起来像这样,但除了用户记录“没有相关的卡”只保存
if (!empty($this->data)) {
foreach($this->data['User']['Card'] as $key => $item){
$this->data['User']['Card'][$key] = array('id'=>$item, 'user_id'=>$this->data['User']['id']);
}
if ($this->User->saveAll($this->data)) {
//$this->User->Card->saveAll($this->data);
$this->Session->setFlash(__('The user has been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->User->read(null, $id);
$this->set('cards', $this->User->Card->find('list'));
}
$ this-> data包含:
Array
(
[User] => Array
(
[id] => 1
[name] => Superman
[status] => 1
[Card] => Array
(
[0] => Array
(
[id] => 11402130001
[user_id] => 1
)
[1] => Array
(
[id] => 11402130002
[user_id] => 1
)
[2] => Array
(
[id] => 11402130003
[user_id] => 1
)
[3] => Array
(
[id] => 11402130004
[user_id] => 1
)
)
)
)
1 回答
您需要为卡添加user_id条目,以便您的数据看起来像这样:
我会在$ this-> data ['Card]数组上进行foreach循环:
然后你可以做你的saveAll . 顺便说一句,应该删除$ this-> User-> Card-> saveAll($ this-> data) .