尝试使用 Transaction()制作API,以提高数据库的安全性。
代码:
DatabaseName::transaction(function () {
$CheckExistingData = PostCustomer::select('Mobile')->where('Mobile', $Mobile);
return $CheckExistingData;
});
错误:
BadMethodCallException in Builder.php line 2258:
Call to undefined method Illuminate\Database\Query\Builder::transaction()
分享你的想法!
PostCustomer是MODEL
PostCustomer模型
class PostCustomer extends Model
{
protected $table = "Customer";
}
"的客户"是表名。
答案 0 :(得分:1)
我试过这样的事情,试试这段代码
PostCustomer::beginTransaction();
try{
$result = true;
PostCustomer::commit();
}catch(Exception $exception)
{
PostCustomer::rollBack();
$errormsg = 'Database error!! ' . $exception->getMessage();
$result = false;
}
交易方法不会像这样工作:请参阅此https://laravel.com/docs/4.2/database#database-transactions。
您可以使用transaction method
或you may need to begin a transaction yourself
。
答案 1 :(得分:1)
问题是Database\Connection中提供了transaction
方法,而您的模型是Eloquent的实例。
因此,PostCustomer
没有交易方法。您应该致电DB
(这是可以访问Database\Connection
和transaction
方法的外观。
你应该这样做:
DB::transaction(function () {
$CheckExistingData = PostCustomer::select('Mobile')->where('Mobile', $Mobile);
return $CheckExistingData;
});
并导入DB
门面当然。
此外,您不需要try/catch
表达式:
注意:事务闭包中抛出的任何异常都会导致事务自动回滚。
PS: (仅当您使用MySQL时)
可能使用交易是不够的:
交易中的
SELECT
查询本身未被UPDATEs
和DELETEs
屏蔽。
(source)