php - 在 ZF2 中使用 WHERE 和 JOIN 进行更新

标签 php mysql zend-framework2

我正在尝试在 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 方法。

引用:Zend\Db\Sql\Update

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

为了使用 tableGateway 通过连接进行更新而不扩展 ZF2 对象,您需要执行如下操作

引用:ZF2 Documentation

<?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 Documentation

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/

相关文章:

php - MySQL 和 PHP : Unkown Column in WHERE clause, 但列确实存在

php - 如何在 Zend Framework 表单中创建日期时间验证器?

php - 全文mysql搜索并匹配精确的字符串

php - Yii2:为什么 auth 键在 User 类中?

php - 无法在 ZF2 中使用控制台

php - Mysql 2个时间字段之间包括第二天

mysql - 在mysql中创建一个函数

php - 将单客户 Web 应用程序转变为多客户应用程序

php - 使用 ZF2 保存到多个表时检查空值

php - 为什么我在远程服务器上运行 Zend Framework 2 应用程序时收到错误 : table doesn't exist,?