1
我GOOGLE了这个有很多,但似乎没有是类似我所期待的..在使用一次如何使用cakephp hasMany一次链接多个记录?
我所试图做的是一个创纪录的“用户”与其他多个记录“卡”链接多个HTML列表。
表是: 用户(ID,姓名,用户名) 卡(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'));
}
$这个 - >数据包含保存什么,但用户记录:
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
)
)
)
)
谢谢G.J但它不起作用!我之前尝试过,但它不保存user_id任何想法是什么问题?我正在使用1.3.4 – mmahgoub 2012-01-15 17:05:11
@mmahgoub如果将Card阵列放在User数组之外,该怎么办?无论如何,我不确定它会工作。如果没有,也许你应该尝试通过尝试保存卡而不是用户来改变你的行为方式。告诉我它是否有效。 – 2012-01-15 21:18:43
嗨GJ实际上它工作,如果它是这样的:'if($ this-> user-> saveAll($ this-> data ['User'])){this-> Session-> setFlash(__('用户已被保存',true));}'但又来了另一个问题! CakePHP不识别未选定的项目,换句话说,当我选择它们时它可以将卡片链接到用户,但是当我删除选择时不会取消链接!任何想法如何实现这个没有foreach循环和saveField和这种东西? – mmahgoub 2012-01-15 22:08:11