2012-03-27 61 views
0

嗨,我只是想知道是否有可能保存hasMany的多個數據:如果可能什麼是數組結構在執行$ this-> Model-> saveAll($ this- >數據)。cakePHP使用hasMany函數保存所有數據

的例子是,你要在這樣的時刻保存多個帖子:

array(
    [Post] => Array 
    (
     [0] => Array 
      (
       [title] => title One 
       [content] => desc One 
      ) 

     [1] => Array 
      (
       [title] => title two 
       [content] => desc two 
      ) 

    ) 

所以定數組中上面我們可以保存所有與白水的職位,但如果每一個職位你有什麼的hasMany評論各。數組應該什麼樣子,如果我要插入下面的數組:

array(
    [Comment] => Array 
    (
     [0] => Array 
      (
       [comment] => 1st Comment for Post One 
      ) 


     [1] => Array 
      (
       [comment] => 2nd Comment for Post One 
      ) 


     [2] => Array 
      (
       [comment] => 1st Comment for Post Two 
      ) 


     [3] => Array 
      (
       [comment] => 2nd Comment for Post Two 
      ) 

    ) 

我怎樣才能將二者結合起來陣列執行白水(); 在此先感謝。^_^

回答

2

假設協會「後有很多的意見」被稱爲"Comments",數據會看起來像

array(
    'Post' => array(
     array(
      'title' => 'title1', 
      'content' => 'content1', 
      'Comments' => array(
       array('comment'=>'1st comment for post 1'), 
       array('comment'=>'2nd comment for post 1'), 
      ), 
     array(
      'title' => 'title2', 
      'content' => 'content2', 
      'Comments' => array(
       array('comment'=>'1st comment for post 2'), 
       array('comment'=>'2nd comment for post 2'), 
      ), 
     ), 
    ), 
) 

爲了節省您可以使用類似:

$this->Model->saveMany($data, array('deep'=>TRUE)); 

注「深層」選項需要CakePHP 2.1。沒有它,關聯的評論記錄將不會被保存。

所有這些都記錄在http://book.cakephp.org/2.0/en/models/saving-your-data.html

+0

謝謝,我會試試這個 – 2012-03-27 15:13:14