Transaction () - Query Builder in laravel 5 throwi

2019-07-24 02:06发布

Trying to make an API using Transaction() for making more security for database.

Code :

    DatabaseName::transaction(function () {

   $CheckExistingData = PostCustomer::select('Mobile')->where('Mobile', $Mobile);

  return $CheckExistingData;
  });

Error :

BadMethodCallException in Builder.php line 2258:

Call to undefined method Illuminate\Database\Query\Builder::transaction()

Share your thoughts!

PostCustomer is MODEL

PostCustomer Model

class PostCustomer extends Model
{
protected $table = "Customer";
}

"Customer" is table name .

2条回答
仙女界的扛把子
2楼-- · 2019-07-24 02:49

I tried something like this, try with this code

PostCustomer::beginTransaction();
try{
    $result = true;
    PostCustomer::commit();
}catch(Exception $exception)
{
    PostCustomer::rollBack();
    $errormsg = 'Database error!! ' . $exception->getMessage();
    $result = false;
}

Transaction method will not work like this : See this https://laravel.com/docs/4.2/database#database-transactions.

Either you can use transaction method or you may need to begin a transaction yourself.

查看更多
萌系小妹纸
3楼-- · 2019-07-24 03:03

The problem is that transaction method is available in Database\Connection and your model is an instance of Eloquent.

Therefore, PostCustomer doesn't have the transaction method. You should call DB (that's the facade that gives you access to Database\Connection and the transaction method.

You should do something like this:

DB::transaction(function () {
    $CheckExistingData = PostCustomer::select('Mobile')->where('Mobile', $Mobile);
    return $CheckExistingData;
});

and import DB facade of course.

Also you don't need a try/catch expression:

Note: Any exception thrown within the transaction closure will cause the transaction to be rolled back automatically.

PS: (only if you're using MySQL)

Probably using a transaction is not enough:

A SELECT query inside a transaction, in itself, is not properly shielded from UPDATEs and DELETEs.

(source)

查看更多
登录 后发表回答