我正在尝试在 Zend Framework 2 中更新 MySQL 数据库中的值。我想在表中使用 where 和 Join 。表结构为
-----Credit-----
ContactID
Credits
-----Token------
ContactID
Token
我想编写以下 MYSQL 查询
"Update credit_details
LEFT JOIN token ON token.CONTACT_ID = credit.CONTACT_ID
SET CREDITS = '200'
WHERE TOKEN ='$token';".
到目前为止,我有以下代码,但它似乎不起作用。
$this->tableGateway->update(function (Update $update) use ($token){
$update->set(array('CREDITS'=>$credits))
->join('token','token.CONTACT_ID=credit.CONTACT_ID', array( 'CONTACT_ID'=>'CONTACT_ID'
),'left')
->where($this->tableGateway->getAdapter()->getPlatform()->quoteIdentifierChain(array('token_details','TOKEN')) . ' = ' . $this->tableGateway->getAdapter()->getPlatform()->quoteValue($token));
});
最佳答案
进行一些澄清。没有用于 UPDATE with JOIN 的抽象层。 Zend Update DBAL 没有可调用的 join 方法。
为了使用 ZF2 的表网关通过联接执行更新,您需要扩展表网关并编写自己的 updateJoin 方法,或者扩展 Sql\Update 对象(如 UpdateJoin)并添加联接方法。
为了使用 tableGateway 通过连接进行更新而不扩展 ZF2 对象,您需要执行如下操作
<?php
/* Define a token for the example */
$token = 12345;
/* create a new statement object with the current adapter */
$statement = $this->tableGateway->getAdapter()
->createStatement(
'UPDATE credit_details
LEFT JOIN token
ON token.CONTACT_ID = credit_details.CONTACT_ID
SET credit_details.CREDITS = 100
WHERE token.TOKEN = ?'
);
/* create a new resultset object to retrieve results */
$resultSet = new Zend\Db\ResultSet\ResultSet;
/* execute our statement with the token and load our resultset */
$resultSet->initialize( $statement->execute( array( $token ) ) );
/* display the affected rows */
echo $resultSet->count();
偏离主题
同时提供一些建议,可以为您节省将来的一些麻烦。当使用 ZF2 DBAL 并且您指定了适配器和驱动程序时,驱动程序将为您处理引用标识符和值。除非您专门使用 Zend\Db\Sql\Expression 或 Zend\Db\Sql\Literal 来处理引用标识符和值。 大多数情况下你可以在where调用中使用Zend\Db\Sql\Predicate\Predicate,这是我更喜欢的方法。
EG:
<?php
$adapter = new Zend\Db\Adapter\Adapter($configArray);
$sql = new Zend\Db\Sql\Sql($adapter);
$update = $sql->update( 'credit_details');
$update->set( array('CREDITS' => $credits) );
$update->where( array( 'CONTACT_ID' => $contact_id ) );
关于php - 在 ZF2 中使用 WHERE 和 JOIN 进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17401339/