Skip to content

Commit fc124ad

Browse files
add transaction
1 parent 8bd7fc1 commit fc124ad

1 file changed

Lines changed: 18 additions & 2 deletions

File tree

src/Database/Model.php

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55
namespace Effectra\Core\Database;
66

77
use Bmt\NounConverter\NounConverter;
8+
use Effectra\Core\Application;
89
use Effectra\Database\Data\DataRules;
10+
use Effectra\Database\DB;
911

1012
/**
1113
* Class Model
@@ -14,7 +16,7 @@
1416
*/
1517
class Model
1618
{
17-
protected static $table = "default";
19+
protected static $table = "default";
1820

1921
/**
2022
* @param array $data represent model data
@@ -63,7 +65,7 @@ public static function display()
6365
*/
6466
public static function getTableName(): string
6567
{
66-
if(static::$table !== 'default'){
68+
if (static::$table !== 'default') {
6769
return static::$table;
6870
}
6971
$modelClass = new static;
@@ -80,4 +82,18 @@ public function collection(): ModelCollection
8082
{
8183
return new ModelCollection($this->data);
8284
}
85+
86+
public function transaction($tableName, $callback)
87+
{
88+
$db = Application::container()->get(DB::class);
89+
try {
90+
$db()->beginTransaction();
91+
call_user_func($callback, $tableName, $callback);
92+
$db()->commit();
93+
} catch (\Throwable $e) {
94+
if ($db()->inTransaction()) {
95+
throw new \Exception($e->getMessage());
96+
}
97+
}
98+
}
8399
}

0 commit comments

Comments
 (0)