Is it possible to build INSERT INTO SELECT query with Doctrine QueryBuilder?

Viewed 3458

I have some Criteria and need to create INSERT query based on SELECT with that Criteria.

Query should be like this:

INSERT INTO mytable (field1, field2)
SELECT f1, f2
FROM mytable2
JOIN mytable3 ON mytable3.field3 = mytable2.field2
WHERE mytable3.somefield = 'somevalue'

EDIT:

I know how to build INSERT INTO VALUES query. But I have conditions for SELECT in Criteria object and I need use them for building INSERT.

I need something like this

public function myInsert(Criteria $criteria)
    $qb = new QueryBuilder;
    $qb->insert('mytable')
        ->values('field1, field2') // Is it possible 
        ->select('f1, f2')         // somthing like this?
        ->from('mytable2')
        ->innerJoin('mytable2', 'mytable3', 'mytable3', 
            'mytable3.field3 = mytable2.field2')
        ->where($criteria);
    $qb->execute();
}
1 Answers

I think you have to build your own statements. It should be something like this.

            $sql ="INSERT INTO mytable (field1, field2)
                   SELECT f1, f2
                   FROM mytable2
                   JOIN mytable3 ON mytable3.field3 = mytable2.field2
                   WHERE mytable3.somefield = 'somevalue'";
            /** @var Connection $connection */
            $connection = GeneralUtility::makeInstance(ConnectionPool::class)
                ->getConnectionForTable(self::TABLENAME);
            /** @var DriverStatement $statement */
            $statement = $connection->prepare($sql);
            $statement->execute();
Related