0

0

Laravel Eloquent模型中乐观锁的实现

藏色散人

藏色散人

发布时间:2023-04-21 15:53:05

|

1165人浏览过

|

来源于learnku

转载

本篇文章给大家带来了关于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方式:

STORYD
STORYD

帮你写出让领导满意的精美文稿

下载
 $ord = Order::find(1);
 $ord->payment_status = 1;
 if(!$model->setOptimisticRaw('payment_status = ?',[1]))->save())
   throws new Exception('订单已付过款了');

如果同一对象小涉及到多次更新,则可以清除锁条件

$ord->clearOptimistic();

以上就是乐观锁的实现方式,在实际开发中比较常用也很有必要。

推荐学习:《laravel视频教程

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
laravel组件介绍
laravel组件介绍

laravel 提供了丰富的组件,包括身份验证、模板引擎、缓存、命令行工具、数据库交互、对象关系映射器、事件处理、文件操作、电子邮件发送、队列管理和数据验证。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

319

2024.04.09

laravel中间件介绍
laravel中间件介绍

laravel 中间件分为五种类型:全局、路由、组、终止和自定。想了解更多laravel中间件的相关内容,可以阅读本专题下面的文章。

278

2024.04.09

laravel使用的设计模式有哪些
laravel使用的设计模式有哪些

laravel使用的设计模式有:1、单例模式;2、工厂方法模式;3、建造者模式;4、适配器模式;5、装饰器模式;6、策略模式;7、观察者模式。想了解更多laravel的相关内容,可以阅读本专题下面的文章。

372

2024.04.09

thinkphp和laravel哪个简单
thinkphp和laravel哪个简单

对于初学者来说,laravel 的入门门槛较低,更易上手,原因包括:1. 更简单的安装和配置;2. 丰富的文档和社区支持;3. 简洁易懂的语法和 api;4. 平缓的学习曲线。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

374

2024.04.10

laravel入门教程
laravel入门教程

本专题整合了laravel入门教程,想了解更多详细内容,请阅读专题下面的文章。

85

2025.08.05

laravel实战教程
laravel实战教程

本专题整合了laravel实战教程,阅读专题下面的文章了解更多详细内容。

65

2025.08.05

laravel面试题
laravel面试题

本专题整合了laravel面试题相关内容,阅读专题下面的文章了解更多详细内容。

68

2025.08.05

数据分析工具有哪些
数据分析工具有哪些

数据分析工具有Excel、SQL、Python、R、Tableau、Power BI、SAS、SPSS和MATLAB等。详细介绍:1、Excel,具有强大的计算和数据处理功能;2、SQL,可以进行数据查询、过滤、排序、聚合等操作;3、Python,拥有丰富的数据分析库;4、R,拥有丰富的统计分析库和图形库;5、Tableau,提供了直观易用的用户界面等等。

707

2023.10.12

俄罗斯Yandex引擎入口
俄罗斯Yandex引擎入口

2026年俄罗斯Yandex搜索引擎最新入口汇总,涵盖免登录、多语言支持、无广告视频播放及本地化服务等核心功能。阅读专题下面的文章了解更多详细内容。

15

2026.01.28

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Laravel 5.8 中文文档手册
Laravel 5.8 中文文档手册

共74课时 | 88万人学习

Laravel---API接口
Laravel---API接口

共7课时 | 0.6万人学习

PHP自制框架
PHP自制框架

共8课时 | 0.6万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号