gpt4 book ai didi

php - Laravel:将我的所有代码放入数据库事务中是一种好习惯吗?甚至没有数据库查询代码?

转载 作者:可可西里 更新时间:2023-11-01 07:06:50 25 4
gpt4 key购买 nike

我正在创建订阅和组队!系统。

伪代码如下:

    $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...

现在我希望所有查询都在数据库事务中执行。我可以将以上所有代码放在 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(明确地)。

关于php - Laravel:将我的所有代码放入数据库事务中是一种好习惯吗?甚至没有数据库查询代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48402237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com