2011-08-13 34 views
5

我有兩個表AccommodationFacility,它們與第三個表Accommodation_facility以多對多關係連接。如何將多個記錄同時插入表中?

  • 住宿(accommodation_id,住宿類別,名稱)
  • 基金(facility_id,facility_name)
  • Accommodation_facility(accommodation_idfacility_id

使用Yii,如何你可以插入多個數據記錄到Accomodation_facility表?

回答

-2

由於你的問題被標記爲「yii」,我猜你正在使用Yii Framework。在文檔中查看Active Records over - http://www.yiiframework.com/doc/guide/1.1/en/database.ar

請按照文檔爲您的表設置AR類,並簡單地循環提交您的複選框列表時發佈的數據。在此循環中,您可以爲要插入數據的表創建,填充和保存AR對象。

0
foreach($facilities as $facility) 
{ 
    $model = new Model; 
    $model->attributes = $facility // or $model->column = $facility 
    if ($model->validate()) 
     $model->save() 
} 
+0

只有一條記錄將被插入。可能是最後一個。 –

+3

應該有'$ model-> isNewRecord = true;'以便在循環中添加多條記錄。 –

11

使用循環插入非常緩慢。假設你有5000行插入,這將花費6分鐘左右的時間(每個記錄單獨插入)。最好用單個查詢插入數據:

$values = '(null, "your string"), (null, "next string"), (null, "third string")'; 
$sql = 'INSERT INTO table_data (id, data) VALUES ' . $values; 
$command = Yii::app()->db->createCommand($sql); 
$command->execute(); 

這將花費1/10的時間。

+0

更好的表述是使用'$ command-> bindValues'和佔位符,然後使用原始數據來防止SQL注入。 – FelikZ

2

您最好不得不使用bindParam來阻止SQL注入。我不知道這是否是最好的方式,但我有這樣做的方式:

$values = array(array(1,2),array(3,4),array(5,6),); 
$nbValues = count($values); 
$sql = 'INSERT INTO table_name (col_name1, col_name2) VALUES '; 
for ($i=0; $i < $nbValues; $i++) { 
    $sql .= '(:col1_'.$i.', :col2_'.$i.')'; 
    if ($i !== ($nbValues-1)) 
     $sql .= ','; 
} 
$command = Yii::app()->db->createCommand($sql); 
for ($i=0; $i < $nbValues; $i++) { 
    $command->bindParam(':col1_'.$i, $values[$i][0], PDO::PARAM_INT); 
    $command->bindParam(':col2_'.$i, $values[$i][1], PDO::PARAM_INT); 
} 
$command->execute(); 

希望這有助於!

相關問題