Search code examples
symfonypropel

How can I issue one Insert statement for multiple rows in Propel


is there a way to issue one INSERT statement instead of calling save() method on each object? Can I call save() on PropelObjectCollection?


Solution

  • You can call save on a PropelObjectCollection from the class itself but it will issue multiple insert statements to do the work.

    There is not much of a performance gain from issuing one INSERT rather than multiple if they are all wrapped in a transaction which Propel does by default. Also given the way Propel recurses to save related objects I suspect trying to do this would add a lot of complexity.

    <?php
    
    /**
     * This file is part of the Propel package.
     * For the full copyright and license information, please view the LICENSE
     * file that was distributed with this source code.
     *
     * @license    MIT License
     */
    
    /**
     * Class for iterating over a list of Propel objects
     *
     * @author     Francois Zaninotto
     * @package    propel.runtime.collection
     */
    class PropelObjectCollection extends PropelCollection
    {
        /**
         * Save all the elements in the collection
         *
         * @param PropelPDO $con
         *
         * @throws PropelException
         */
        public function save($con = null)
        {
            if (!method_exists($this->getModel(), 'save')) {
                throw new PropelException('Cannot save objects on a read-only model');
            }
            if (null === $con) {
                $con = $this->getConnection(Propel::CONNECTION_WRITE);
            }
            $con->beginTransaction();
            try {
                /** @var $element BaseObject */
                foreach ($this as $element) {
                    $element->save($con);
                }
                $con->commit();
            } catch (PropelException $e) {
                $con->rollback();
                throw $e;
            }
        }