Database transactions in Zend Framework: Are they isolated?

后端 未结 1 1442
野趣味
野趣味 2020-12-30 13:31

Using Zend Framework, I need to (1) read a record from a MySQL database, and (2) immediately write back to that record to indicate that it has been read. I don\'t want other

1条回答
  •  醉梦人生
    2020-12-30 13:54

    Presupposing you are using the InnoDB engine for tables that you will issue transactions on:

    If the requirement is that you first need to read the row and exclusively lock it, before you are going to update it, you should issue a SELECT ... FOR UPDATE query. Something like:

    $db->beginTransaction();
    try
    {
        $select = $db->select()
                     ->forUpdate() // <-- here's the magic
                     ->from(
                         array( 'a' => 'yourTable' ),
                         array( 'your', 'column', 'names' )
                     )
                     ->where( 'someColumn = ?', $whatever );
    
        $result = $this->_adapter->fetchRow( $select );
    
        /*
          alter data in $result
          and update if necessary:
        */
        $db->update( 'yourTable', $result, array( 'someColumn = ?' => $whatever ) );
    
        $db->commit();
    }
    catch( Exception $e )
    {
        $db->rollBack();
    }
    

    Or simply issue 'raw' SELECT ... FOR UPDATE and UPDATE SQL statements on $db of course.

    0 讨论(0)
提交回复
热议问题