Doctrine - insert multiple rows with just one save

2020-02-03 06:02发布

问题:

How do I insert multiple rows into table calling save() method once in Doctrine?

回答1:

Add each record to a Doctrine_Collection the call save() on the collection object.

$collection = new Doctrine_Collection('tablename');
$collection->add($record1);
$collection->add($record2);
$collection->add($record3);
$collection->add($record4);
$collection->save();

This only works if all the records are for the same table. Otherwise you're out of luck.



回答2:

Here another solution ,tested on Doctrine 1.2. No need to save each records, the flush() automatically finds out all the unsaved instances and saves them all.

$row = new \My_Doctrine_Record();
$row->name = 'aaa';
$row->approved = 1;

/// ...

$row = new \My_Doctrine_Record();
$row->name = 'val';
$row->approved = 'bbb';

Doctrine_Manager::connection()->flush();


回答3:

If you use symfony2 it is so easy

// get the manager
$em = $this->getDoctrine()->getManager();

// enter the records
$em->persist($entitiy1);
$em->persist($entitiy2);
$em->persist($entitiy3);
$em->persist($entitiy4);
$em->persist($entitiy5);

// save the entries
$em->flush();


回答4:

1)Declare all the tables. 2)Create the form. 3)Send to multiple tables. 4)Persist data.

use AppBundle\Entity\site;
use AppBundle\Entity\nba;

1)Declare all the tables.

 $site = new site;
 $nba = new nba;

2)Create form

$form = $this->createFormBuilder($site)




    ->add('site_id', IntegerType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px')))
    ->add('category', ChoiceType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px'), 'choices' => $output))
    ->add('team', ChoiceType::class, array('attr' => array('class' => 'form-control', 'style' => 'margin-bottom:15px'), 'choices' => $nbat))
    ->add('save', SubmitType::class, array('label' => "Create",'attr' => array('class' => 'btn btn-success', 'style' => 'margin-bottom:15px')))
    ->getForm();
    $form->handleRequest($request);
    if($form->isSubmitted() && $form->isValid())

3)Insert into multiple tables.

    {

        $site_id = $form['site_id']->getData();
        $category = $form['category']->getData();
        $team = $form['team']->getData();




        $site->setSiteId($site_id);
        $site->setCategory($category);
        $nba->setWinner($team);

4)Persist data

            $em = $this->getDoctrine()->getManager();
            $em->persist($site);
            $em->persist($nba);
            $em->flush();


回答5:

I took a look into the code of the "save" method of the Doctrine (1.2.x) "Collection.php" and all I saw is something like this:

foreach ($this->getData() as $key => $record) {
   $record->save($conn);
}

How should this ever insert all records with one mysql INSERT?