Laravel Eloquent模型中乐观锁的实现
本篇文章给大家带来了关于Laravel的相关知识,其中主要跟大家介绍Laravel Eloquent模型中乐观锁的实现,有代码示例,感兴趣的朋友下面一起来看一下吧,希望对大家有帮助。
在app/Utils/Traits目录下创建OptimisticLockTrait.php,代码如下:
namespace App\Utils\Traits;use Illuminate\Database\Eloquent\Builder;trait OptimisticLockTrait{ /** * @var array $optimisticConditions * @var array $bindings */ protected $optimisticConditions, $bindings; /** * @var string $optimisticConditionRaw */ protected $optimisticConditionRaw; /** * save 时增加乐观锁条件 * @param Builder $builder */ protected function performUpdate(Builder $builder) { if (!empty($this->optimisticConditions)) { foreach ($this->optimisticConditions as $field => $value) { if (is_array($value)) { $count = count($value); if ($count >= 3) { switch (strtoupper($value[1])) { case 'IN': $builder->whereIn($value[0], $value[2]); break; case 'NOT IN': $builder->whereNotIn($value[0], $value[2]); break; case 'BETWEEN': $builder->whereBetween($value[0], $value[2]); break; case 'NOT BETWEEN': $builder->whereNotBetween($value[0], $value[2]); break; default: $builder->where($value[0], $value[1], $value[2]); } } else { $builder->where($value); } } else { $builder->where($field, $value); } } } // 原始条件注入 if ($this->optimisticConditionRaw) $builder->whereRaw($this->optimisticConditionRaw, $this->bindings); return $this->clearOptimistic()->perFormUpdating($builder); } /** * updating with optimistic * * @param Builder $builder * @return bool */ protected function perFormUpdating(Builder $builder) { // If the updating event returns false, we will cancel the update operation so // developers can hook Validation systems into their models and cancel this // operation if the model does not pass validation. Otherwise, we update. if ($this->fireModelEvent('updating') === false) { return false; } // First we need to create a fresh query instance and touch the creation and // update timestamp on the model which are maintained by us for developer // convenience. Then we will just continue saving the model instances. if ($this->usesTimestamps()) { $this->updateTimestamps(); } // Once we have run the update operation, we will fire the "updated" event for // this model instance. This will allow developers to hook into these after // models are updated, giving them a chance to do any special processing. $dirty = $this->getDirty(); $res = 0; if (count($dirty) > 0) { $res = $this->setKeysForSaveQuery($builder)->update($dirty); $this->syncChanges(); $this->fireModelEvent('updated', false); } return !empty($res); } // 清除乐观锁条件 function clearOptimistic() { $this->optimisticConditions = null; $this->optimisticConditionRaw = null; return $this; } // 设置乐观锁条件字段名列表 function setOptimistic(array $optimisticConditions) { $this->optimisticConditions = $optimisticConditions; return $this; } // 设置乐观锁原始条件字段名列表 function setOptimisticRaw(string $optimisticConditionRaw, array $bindings = []) { $this->optimisticConditionRaw = $optimisticConditionRaw; $this->bindings = $bindings; return $this; }}
乐观锁使用说明
1、在模型中(Models)或模型父类使用
/** * App\Models\BaseModel * @mixin \Eloquent * @method static \Illuminate\Database\Eloquent\Builder|BaseModel newModelQuery() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel newQuery() * @method static \Illuminate\Database\Eloquent\Builder|BaseModel query() */class BaseModel extends Model{ use OptimisticLockTrait;}
2、使用方法:
$ord = Order::find(1); $ord->payment_status = 1; if(!$model->setOptimistic(['payment_status' => 0]))->save()) throws new Exception('订单已付过款了');
或者使用原始SQL方式:
$ord = Order::find(1); $ord->payment_status = 1; if(!$model->setOptimisticRaw('payment_status = ?',[1]))->save()) throws new Exception('订单已付过款了');
如果同一对象小涉及到多次更新,则可以清除锁条件
$ord->clearOptimistic();
以上就是乐观锁的实现方式,在实际开发中比较常用也很有必要。
推荐学习:《laravel视频教程》
以上是Laravel Eloquent模型中乐观锁的实现的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

热门话题

使用ORM可简化PHP中的数据库操作,它将对象映射到关系数据库中。Laravel中的EloquentORM允许使用面向对象的语法与数据库交互,可通过定义模型类、使用Eloquent方法或在实战中构建博客系统等方式来使用ORM。

Laravel9和CodeIgniter4的最新版本提供了更新的特性和改进。Laravel9采用MVC架构,提供数据库迁移、身份验证和模板引擎等功能。CodeIgniter4采用HMVC架构,提供路由、ORM和缓存。在性能方面,Laravel9的基于服务提供者设计模式和CodeIgniter4的轻量级框架使其具有出色的性能。在实际应用中,Laravel9适用于需要灵活性和强大功能的复杂项目,而CodeIgniter4适用于快速开发和小型应用程序。

Laravel - Artisan 命令 - Laravel 5.7 提供了处理和测试新命令的新方法。它包括测试 artisan 命令的新功能,下面提到了演示?

比较Laravel和CodeIgniter的数据处理能力:ORM:Laravel使用EloquentORM,提供类对象关系映射,而CodeIgniter使用ActiveRecord,将数据库模型表示为PHP类的子类。查询构建器:Laravel具有灵活的链式查询API,而CodeIgniter的查询构建器更简单,基于数组。数据验证:Laravel提供了一个Validator类,支持自定义验证规则,而CodeIgniter的验证功能内置较少,需要手动编码自定义规则。实战案例:用户注册示例展示了Lar

对于初学者来说,CodeIgniter的学习曲线更平缓,功能较少,但涵盖了基本需求。Laravel提供了更广泛的功能集,但学习曲线稍陡。在性能方面,Laravel和CodeIgniter都表现出色。Laravel具有更广泛的文档和活跃的社区支持,而CodeIgniter更简单、轻量级,具有强大的安全功能。在建立博客应用程序的实战案例中,Laravel的EloquentORM简化了数据操作,而CodeIgniter需要更多的手动配置。

在选择大型项目框架时,Laravel和CodeIgniter各有优势。Laravel针对企业级应用程序而设计,提供模块化设计、依赖项注入和强大的功能集。CodeIgniter是一款轻量级框架,更适合小型到中型项目,强调速度和易用性。对于具有复杂需求和大量用户的大型项目,Laravel的强大功能和可扩展性更合适。而对于简单项目或资源有限的情况下,CodeIgniter的轻量级和快速开发能力则更为理想。

PHP单元和集成测试指南单元测试:关注单个代码单元或函数,使用PHPUnit创建测试用例类进行验证。集成测试:关注多个代码单元协同工作的情况,使用PHPUnit的setUp()和tearDown()方法设置和清理测试环境。实战案例:使用PHPUnit在Laravel应用中进行单元和集成测试,包括创建数据库、启动服务器以及编写测试代码。

对于小型项目,Laravel适用于大型项目,需要强大的功能和安全性。CodeIgniter适用于非常小的项目,需要轻量级和易用性。
