我正在创建一个订阅和团队!系统.
这是伪代码:
$sub = Sub::create($sub_data);
if(request for new team){
$team = Team:create($team_data)
Mail::queue....// sending email and notif
// some PHP code here
}
elseif(request to join a team)
{
$team = Team:find($team_data)
$team->subscriber()->create($team_data) // a team has many subscribers
Mail::queue....// sending email and notif
// some PHP code here
}
// Here some extra queries...
现在我希望所有查询都在DB事务中执行.我可以将所有上述代码放在Laravel Transaction闭包中吗?
DB::transaction(function()
{
// all the above code here
});
最佳答案
根据Laravel文档:
原文链接:https://www.f2er.com/mysql/432892.htmlYou may use the transaction method on the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction Closure,the transaction will automatically be rolled back. If the Closure executes successfully,the transaction will automatically be committed.
当您正在进行的数据库操作集需要是原子时,您可以使用事务.
那就是 – 他们都需要成功或失败.介于两者之间.
事务将用于确保数据库始终处于一致状态.
始终是创建交易的不良做法?
这取决于你在这里谈论的背景.如果是更新,那么我强烈建议明确使用TRANSACTIONS.如果它是SELECT然后NO(显式).