ZF2 - How do I insert into select?

时间:2015-07-28 23:17:28

标签: php mysql zend-framework2

I am trying to perform an insert into select from a table method in zf2.

The following procedure is what I used as an example.

How to perform an INSERT INTO SELECT query in ZF2

My table method is contained in a table class in ZF2 which is a separate table in the db from the tables I am trying to insert into.

public function addCategoryName($val)
    {
        $data = array ( 
            'CategoryName' => $val);

        $this->tableGateway->insert($data);
        $id = $this->tableGateway->lastInsertValue;

        $on = "categoryid = $id";
        $select = new Select('actionitems');

        $select->columns(array('actionitemid', 'categoryid'))->join('categories', $on, array('actionitemid', 'categoryid'), 'cross'); 

        $adapterInsert = new \Zend\Db\Adapter\Adapter(array(
            'driver'   => 'pdo_mysql',
            'database' => 'actionitemmanager',
            'username' => 'username',
            'password' => 'password'
        ));

        $insert = new Insert();
        $insert->into('actionitemcategories');
        $insert->columns(array('actionitemid', 'categoryid'));
        $insert->values($select);
        //insert with select
        $adapterInsert->insertWith($insert);
    }

Neither

$insert->values($select)

or

$insert->select($select)

work...

The first attempt gives an error that the $select must be an array, whereas $insert->select($select) gives an error that select() is not a method of Insert.

How can I get this query to work?

1 个答案:

答案 0 :(得分:1)

您引用的Zend Framework功能是introduced in v2.3

  

Zend\Db\Sql\Insert可以使用Select对象作为价值来源(INSERT INTO ... SELECT

我怀疑你使用的是旧版本。您可以将v2.2.10中的Zend\Db\Sql\Insertv2.3.0进行比较,以查看针对无效参数引发的不同异常。

您应该将Zend Framework升级到v2.3或更高版本才能使用此功能。