ZF2 Zend\Db Insert/Update Using Mysql Expression (Zend\Db\Sql\Expression?)

◇◆丶佛笑我妖孽 提交于 2020-01-14 07:48:10

问题


Is there any way to include MySQL expressions like NOW() in the current build of ZF2 (2.0.0beta4) through Zend\Db and/or TableGateway insert()/update() statements?

Here is a related post on the mailing list, though it hasn't been answered: http://zend-framework-community.634137.n4.nabble.com/Zend-Db-Expr-and-Transactions-in-ZF2-Db-td4472944.html

It appears that ZF1 used something like:

    $data = array( 
        'update_time'   => new \Zend\Db\Expr("NOW()") 
    ); 

And after looking through Zend\Db\Sql\Expression I tried:

    $data = array(
        'update_time' => new \Zend\Db\Sql\Expression("NOW()"),
    );

But get the following error:

Catchable fatal error: Object of class Zend\Db\Sql\Expression could not be converted to string in /var/www/vendor/ZF2/library/Zend/Db/Adapter/Driver/Pdo/Statement.php on line 256

As recommended here: http://zend-framework-community.634137.n4.nabble.com/ZF2-beta3-Zend-Db-Sql-Insert-new-Expression-now-td4536197.html I'm currently just setting the date with PHP code, but I'd rather use the MySQL server as the single source of truth for date/times.

    $data = array(
        'update_time' => date('Y-m-d H:i:s'),
    );

Thanks, I appreciate any input!


回答1:


I am not sure if they fixed this in the latest updates, but it was a know bug and even if they said it was fixed, for me it still didn't work after the fix.




回答2:


Zend_Db_Sql_Expression works for me now.

$data = array(
    'update_time' => new \Zend\Db\Sql\Expression("NOW()"),
);



回答3:


It works for me too. Maybe, your problem was like mine. The string error conversion was because the parameter that I passed to method was elements of array and not the array. Check this and have sure that you are passing $object->method($array).




回答4:


You can try:

\Zend\Db\Sql\Predicate\Literal();
//or
\Zend\Db\Sql\Literal();
------------------------------------
$data = array(
    'update_time' => new \Zend\Db\Sql\Literal("NOW()"),
);

https://framework.zend.com/manual/2.2/en/modules/zend.db.sql.html#literal-literal



来源:https://stackoverflow.com/questions/11183061/zf2-zend-db-insert-update-using-mysql-expression-zend-db-sql-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!