So, I got a series of data that I need to insert into a table. Right now I am using a for loop to iterate through each entry and save the model one by one. But that doesn't seem like a good way to do it, moreover using transaction would be an issue. What's a better way to do it to improve performance and also so I can use transaction.Here's the code I am currently using.

foreach ($sheetData as $data)
    {
        $newRecord = new Main;
        $newRecord->id = $data['A'];
        $newRecord->name = $data['B'];
        $newRecord->unit = $data['C'];
        $newRecord->save();
    }
有帮助吗?

解决方案

If you can skip validation, you can generate a simple sql insert and execute it once. like:

$count = 0;
$sql = '';
foreach ($sheetData as $data)
{
    if(!$count)
       $sql .= 'INSERT INTO tbl_main (id ,name ,unit) Values ('.$data['A'].','$data['B']','$data['C']') ';
    else
       $sql .= ' , ('.$data['A'].','$data['B']','$data['C']')';
    $count++;
}

Yii::app()->db->createCommand($sql)->execute();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top