PHPActiveRecord 学习三

#事务处理 注意事务 数据库要用InnoDB引擎

$c1 = User::connection();

try {
    //开启事务
    $c1->transaction(); 
    //sql语句
    $sql = User::create(
        array("name" => "good_nice")
    );
    //提交事务
    $c1->commit();

} catch (Exception $e) {
    //事务回滚
    $c1->rollback();
    throw $e;
}    

  源码 lib/Connection.php

abstract class Connection
{
	......
	....
	..
	/**
	 * Starts a transaction.
	 */
	public function transaction()
	{
		if (!$this->connection->beginTransaction())
			throw new DatabaseException($this);
	}

	/**
	 * Commits the current transaction.
	 */
	public function commit()
	{
		if (!$this->connection->commit())
			throw new DatabaseException($this);
	}

	/**
	 * Rollback a transaction.
	 */
	public function rollback()
	{
		if (!$this->connection->rollback())
			throw new DatabaseException($this);
	}
	......
	....
	..
}

  #输出sql语句的三种方法

1. User::table()->conn->last_query  #returns last query to the connection

2. User::connection()->last_query    #same as the first

3. User::table()->last_sql     #this will only return the last query sent to the finder functions and will not include association queries

  

原文地址:https://www.cnblogs.com/foreversun/p/6840764.html