简体   繁体   中英

How to use transaction in Eloquent Model

I use Capsule to manage database connections in my project, and use Model to operate databases, like this:

// Init Eloquent ORM Connection
$capsule = new Capsule;
$capsule->addConnection(Config::getDbConfig());
$capsule->addConnection(Config::getRadiusDbConfig(), 'radius');
$capsule->bootEloquent();

I want to use transaction while executing a large modification to database, but there're no related methods in the class Model.

Because of the Capsule, I'm not able to use Illuminate\\Suooprt\\Facades\\DB , since it reports this error:

PHP Fatal error:  Uncaught RuntimeException: A facade root has not been set. in
E:\Projects\ss-panel\vendor\illuminate\support\Facades\Facade.php:210

How should I deal with it?

I am using Eloquent ORM outside Laravel.

Here is the solution how I start transaction.

You can add an base model extend \\Illuminate\\Database\\Eloquent\\Model.

<?php

use Illuminate\Database\Eloquent\Model as EloquentModel;

class Model extends EloquentModel
{
     public static function beginTransaction()
     {
          self::getConnectionResolver()->connection()->beginTransaction();
     }

     public static function commit()
     {
         self::getConnectionResolver()->connection()->commit();
     }

     public static function rollBack()
     {
         self::getConnectionResolver()->connection()->rollBack();
     }    
}

Then, you can use it like this:

Model::beginTransaction();

//do what you like.

Model::commit();

// OR

Model::rollBack();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM