Laravel 4.2 - 多个数据库的事务回滚问题

时间:2015-06-11 21:26:26

标签: php laravel pdo transactions

我在回滚涉及多个数据库中的表的事务时遇到了问题。主表回滚的行为与预期的一样,但子行仍然存在,现在是孤立的。

public function devUserCreateTest()
{
    DB::beginTransaction();

    try {

        $childUser  = new ChildUser; // Exists in database B
        $parentUser = new User; // Exists in database A

        $parentUser->setEmailAttribute('mike@yourmomshouse.com');

        $parentUser->save();

        $childUser->parent_user_id = $parentUser->id;

        $message = sprintf('Parent user id: %s', serialize($childUser->id));

        $childUser->save();

        $message = sprintf('Core user id: %s | hta user id: %s', serialize($parentUser->id), serialize($childUser->id));

        throw new Exception('Testing....');

        DB::commit();

    } catch (Exception $e) {

        Log::warning(sprintf('Exception: %s', $e->getMessage()));

        DB::rollback();
    }

    return $this->buildResponse(array('message' => $message));
}

看起来很有效:

public function devUserCreateTest()
{
    $dboA = DB::connection();
    $dboB = DB::connection('b_database');

    $dboA->beginTransaction();
    $dboB->beginTransaction();

    try {

        $childUser  = new ChildUser; // Exists in database B
        $parentUser = new User; // Exists in database A

        $parentUser->setEmailAttribute('mike@yourmomshouse.com');

        $parentUser->save();

        $childUser->parent_user_id = $parentUser->id;

        $message = sprintf('Parent user id: %s', serialize($childUser->id));

        $childUser->save();

        $message = sprintf('Core user id: %s | hta user id: %s', serialize($parentUser->id), serialize($childUser->id));

        throw new Exception('Testing....');

        $dboA->commit();
        $dboB->commit();

    } catch (Exception $e) {

        Log::warning(sprintf('Exception: %s', $e->getMessage()));

        $dboA->rollback();
        $dboB->rollback();
    }

    return $this->buildResponse(array('message' => $message));
}

1 个答案:

答案 0 :(得分:2)

您还必须在数据库B上设置事务。

由于您没有发布Begin123456 = to start the device. IMEI123456 = so that the device will return the 15 digits. adminip123456 109.0.0.9 = 8080 to set the ip + port that I am using. 代码,以下是一个示例:

app / models / ChildUser.php:

ChildUser

然后是您的代码

class ChildUser extends Eloquent
{
    protected $connection = 'some_connection'; // as defined in app/config/database.php
}