簡體   English   中英

在ZF2中使用WHERE和JOIN更新

[英]Update with WHERE and JOIN in ZF2

我正在嘗試在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));
    });

給一些澄清。 沒有用於JOIN的UPDATE的抽象層。 Zend Update DBAL沒有要調用的join方法。

參考: Zend \\ Db \\ Sql \\ Update

為了使用ZF2的表網關執行連接更新,您需要擴展表網關並編寫自己的updateJoin方法,或者擴展Sql \\ Update對象,例如說UpdateJoin並添加一個join方法。

為了使用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 ) );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM