0

我正在尝试在 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));
    });
4

1 回答 1

0

澄清一下。UPDATE with JOIN 没有抽象层。Zend Update DBAL 没有可调用的连接方法。

参考:Zend\Db\Sql\Update

为了使用 ZF2 的表网关执行连接更新,您需要扩展表网关并编写自己的 updateJoin 方法或扩展 Sql\Update 对象如 UpdateJoin 并添加一个连接方法。

为了使用 tableGateway 在不扩展 ZF2 对象的情况下通过连接进行更新,您需要执行以下操作

参考: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,这是我的首选方法。

参考:Zend\Db\Sql 文档

例如:

<?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 ) );
于 2014-02-19T21:27:29.620 回答