Friday, September 28, 2012

Multiple record Saving using a loop in CakePHP

Situation :: Suppose, in a sample project, a vendor can have various contacts saved as his reference. We have an array of 10 rows and each of those rows need to be inserted in a database table using a loop. We have a corresponding model "Vendorcontact" where the table name and primary keys have been defined.

Problem :: 
If we use ModelName::save() method inside the loop, it creates a record for the first time in the zeroth iteration of the loop. Next time onwards, it just updates the same record.

Assumption :: 
The array names $vendor_contacts
The related model name is "Vendorcontact"; 
The vendor has an ID 1;
The "Vendorcontact" table has following fields :: vendor_id (INT), vendor_contact (Varchar)

Solution :: 


// Vendor id

$vendor_id = 1;

// Vendor contacts are kept in an Array

$vendor_contacts[0] = "x@x.com";
$vendor_contacts[1] = "xy@xy.com";
...
...
$vendor_contacts[9] = "z@z.com";

// Load corresponding model

$this->loadModel('Vendorcontact');

$a = array(); // 


// Build the loop

for( $i=0; $i < count($vendor_contacts); $i++ )
{
  $a = "";
  $a['vendor_id'] = $vendor_id;
  $a['vendor_contact'] = $vendor_contacts[$i];

  //The important line below tells

  //Cake to INSERT instead of UPDATE 
  $this->Vendorcontact->create(false);  
  $this->Vendorcontact->save( $a );

}

?>

No comments: