How to save multiple entries in table using cake php

370 views Asked by At

How can I save multiple entries in a table using cake php? Here is the code I have written so far.

$err_counter = 1;
$data3 = array();
foreach ($data2['MembershipTime'] as $k => $values) 
     {
            $batch_id = $lastid;
            $day = $values['day'];
            $skip =  (!empty($values['skip']))  ? $values['skip'] : "";
            $h1 =  (!empty($values['h1']))  ? $values['h1'] : "00";
            $m1 =  (!empty($values['m1']))  ? $values['m1'] : "00";
            $h2 =  (!empty($values['h2']))  ? $values['h2'] : "00";
            $m2 =  (!empty($values['m2']))  ? $values['m2'] : "00";

            $data3['BatchesTimes']['batch_id'] = $batch_id;
            $data3['BatchesTimes']['day'] = $day;
            $data3['BatchesTimes']['skip'] = $skip;
            $data3['BatchesTimes']['h1'] = $h1;
            $data3['BatchesTimes']['m1'] = $m1;
            $data3['BatchesTimes']['h2'] = $h2;

            $obj = $this->BatchesTimes->save($data3);
     }
1

There are 1 answers

0
Manasa On BEST ANSWER

Here With a sample Example of my own array i am going to explain you.You change the variables according to the name in your array.

$this->ModelName->saveAll($data3);

If the above solution doesn't Work means try the below solution mentioned in the solved example.

In your case $dataMulti = $data3; Example:

 $dataMulti = array(
        array(
            'Info' =>
            array(
                'note' => "This is note 1",
                'delete_flag' => "f"
            )
        ),
        array(
            'Info' =>
            array(
                'note' => "This is note 2",
                'delete_flag' => "f"
            )
        ),
        array(
            'Info' =>
            array(
                'note' => "This is note 3",
                'delete_flag' => "f"
            )
        ),
    );

Save many records in once time We have two way belows:

1. $infoModel->saveAll($dataMulti);

or

2. $infoModel->saveMany($dataMulti);

Hope it works.