如何使用cakephp hasMany一次链接多个记录?

时间:2012-01-14 18:35:47

标签: cakephp cakephp-1.3

我搜索了很多内容,但似乎没有什么与我想要的相似......

我要做的是使用多个HTML列表将一个记录“User”与其他多个记录“Cards”一起链接。

表格是: 用户(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->数据包含:

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 个答案:

答案 0 :(得分:0)

您需要为卡添加user_id条目,以便您的数据看起来像这样:

Array
(
    [User] => Array
        (
            [id] => 10
        )
    [Card] => Array
        (
            [0] => Array
                (
                [id] => 1
                [user_id] => 10
                )
            [1] => Array
                (
                [id] => 2
                [user_id] => 10
                )

        )
)

我会在$ this-> data ['Card]数组上找到foreach循环:

foreach ($this->data['Card'] as &$card) {
  $card['user_id'] = $this->data['User']['id'];
}

然后你可以做你的saveAll。顺便说一下, $ this-> User-> Card-> saveAll($ this-> data)应该被移除。