What’s the best way to perform an INSERT INTO SELECT query in ZF2?
I need to develop a function in ZF2 that selects a subset of records from one table and inserts those records into another table. If I were programming in SQL, the statement would look like this:
INSERT INTO target (tgt_col1, tgt_col2)
SELECT 'flag' as marker, src_col2 FROM source
WHERE src_col1='mycriteria'
I’ve searched the Doctrine docs and cannot find an INSERT method. I’ve posted a similar question under the Doctrine tag and the lack of response leads me to believe that INSERT INTO SELECT is too complex for Doctrine to handle.
In ZF2 it appears that I “could” useZend\Db\Sql\Sql
. However, for that solution, SELECT
and INSERT
are two separate functions and it looks like the INSERT
function only handles a single record at a time. Therefore, a Zend\Db\Sql\Sql
solution would require 1) a group of statements to select the data from the source table, 2) perhaps a function to convert that data object to an array, and 3) a foreach
function to cycle through the data array and individually add each record to the target table via 4) a group of insert statements. This seems cumbersome compared to the single statement that’s possible in SQL.
Is there a better way?
If its
TableGateway
then it definitely works with the latest version of ZF2 i.e. 2.3.2With reference with the
Album
module -album
and named italbum_old
.album
table.So now
album
table is empty andalbum_old
has the values.To copy the records from
album_old
toalbum
, did this -All the values from
album_old
were inserted intoalbum
table.Ref: https://github.com/zendframework/zf2/blob/master/library/Zend/Db/Sql/Insert.php
Here you will find that the
function values()
can takearray
orinstanceof Select
and there is a new
select()
function too.