2012-08-07 99 views
2

我有三個表,我會插入一個數組到數據庫。它的一個電視節目,有很多季節。季節有許多情節。這裏是我的表:如何將多維數組插入到cakephp 2.2.1數據庫中?

顯示

id 
title 
created 
modified 

賽季

id 
shows_id 
created 
modified 

發作

id 
seasons_id 
title 
created 
modified 

模型文件:

Show.php

<?php 
class Show extends AppModel { 
    public $name = 'Show'; 
    public $hasMany = 'Season'; 
} 

Season.php

<?php 
class Season extends AppModel { 
    public $name  = 'Season'; 
    public $belongsTo = 'Show'; 
    public $hasMany  = 'Episode'; 
} 

Episode.php

<?php 
class Episode extends AppModel { 
    public $name = 'Episode'; 
    public $belongsTo = 'Season'; 
} 

我曾與T試了一下他的陣列:

$this->Show->create(); 

$sql_show = array(
    'Show' => array(
     'id'  => 2, 
     'title'  => 'Super Mega Show', 
    ), 
    'Season' => array(
     array(
      'id'  => 1, 
      'shows_id' => 2, 
      'Episode' => array(
       array(
        'id' => 1, 
        'title' => 'Episode Title 1' 
       ), 
       array(
        'id' => 2, 
        'title' => 'Episode Title 2 ' 
       ), 
       array(
        'id' => 3, 
        'title' => 'Episode Title 3' 
       ), 
      ) 
     ), 
    ) 
); 


$this->Show->saveAll($sql_show); 

我該如何插入這個數組?

問候

+0

試過'serialize'? 編輯:對不起,我誤解了你想要的。 – Prasanth 2012-08-07 10:34:10

+1

爲了這個目的,我會使用兩個表,'shows'和'episodes',否則你必須在你的表中添加'parent_id',其中'parent_id = 0'是一個節目,'parent_id = N'是節目的節目 – Nazariy 2012-08-07 10:36:37

回答

2

你可以試試下面的代碼保存多個相關的數據:

$this->Show->save($sql_show, array('deep' => true)); 

您也可以嘗試使用它的方法saveAssociated()

請問,如果它不適合你。

+1

YESS !!有用!非常感謝你:) '$ this-> Show-> save($ sql_show,array('deep'=> true));'是結果! – poldixd 2012-08-07 21:36:47