加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

php – Laravel:将所有代码放入数据库事务中这是一个好习惯吗

发布时间:2020-12-11 23:50:06 所属栏目:MySql教程 来源:网络整理
导读:我正在创建一个订阅和团队!系统. 这是伪代码: $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

我正在创建一个订阅和团队!系统.

这是伪代码:

    $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 
});

我的意思是有这么多的PHP代码和没有查询逻辑,比如发送电子邮件……这是一个好习惯吗?如果不是,我该怎么办? 最佳答案 根据Laravel文档:

You 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(显式).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读