2012-01-14 73 views
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 
      ) 
     ) 
    ) 
) 

回答

0

您需要添加一個條目的user_id爲您卡,所以您的數據看起來就像是這樣的:

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

     ) 
) 

我會去在$這個 - >數據foreach循環['卡]數組:

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

然後你可以做你的saveAll。順便說一句,$ this-> User-> Card-> saveAll($ this-> data)應該被刪除。

+0

謝謝G.J但它不起作用!我之前嘗試過,但它不保存user_id任何想法是什麼問題?我正在使用1.3.4 – mmahgoub 2012-01-15 17:05:11

+0

@mmahgoub如果將Card陣列放在User數組之外,該怎麼辦?無論如何,我不確定它會工作。如果沒有,也許你應該嘗試通過嘗試保存卡而不是用戶來改變你的行爲方式。告訴我它是否有效。 – 2012-01-15 21:18:43

+0

嗨GJ實際上它工作,如果它是這樣的:'if($ this-> user-> saveAll($ this-> data ['User'])){this-> Session-> setFlash(__('用戶已被保存',true));}'但又來了另一個問題! CakePHP不識別未選定的項目,換句話說,當我選擇它們時它可以將卡片鏈接到用戶,但是當我刪除選擇時不會取消鏈接!任何想法如何實現這個沒有foreach循環和saveField和這種東西? – mmahgoub 2012-01-15 22:08:11