搜索
首页php框架LaravelLaravel Eloquent模型中乐观锁的实现

Laravel Eloquent模型中乐观锁的实现

Apr 21, 2023 pm 03:53 PM
laraveleloquent

本篇文章给大家带来了关于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中文网其他相关文章!

声明
本文转载于:learnku。如有侵权,请联系admin@php.cn删除
包容的幻想:解决偏远工作中的孤立和孤独感包容的幻想:解决偏远工作中的孤立和孤独感Apr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel用于全堆栈开发:综合指南Laravel用于全堆栈开发:综合指南Apr 25, 2025 am 12:27 AM

laravelispularfullull-stackDevelopmentBecapeitOffersAsAseAseAseAseBlendOfbackendEdpoperandPowerandForterFlexibility.1)ITSbackEndCapaPabilities,sightifyDatabaseInteractions.2)thebladeTemplatingEngingEngineAllolowsLows

视频会议摊牌:为远程会议选择正确的平台视频会议摊牌:为远程会议选择正确的平台Apr 25, 2025 am 12:26 AM

选择视频会议平台的关键因素包括用户界面、安全性和功能。1)用户界面应直观,如Zoom。2)安全性需重视,MicrosoftTeams提供端到端加密。3)功能需匹配需求,GoogleMeet适合简短会议,CiscoWebex提供高级协作工具。

哪些数据库版本与最新的Laravel兼容?哪些数据库版本与最新的Laravel兼容?Apr 25, 2025 am 12:25 AM

最新版本的Laravel10与MySQL5.7及以上、PostgreSQL9.6及以上、SQLite3.8.8及以上、SQLServer2017及以上兼容。这些版本选择是因为它们支持Laravel的ORM功能,如MySQL5.7的JSON数据类型,提升了查询和存储效率。

将Laravel用作全栈框架的好处将Laravel用作全栈框架的好处Apr 25, 2025 am 12:24 AM

laravelisanexceltentchoiceforfull-stackdevelopmentduetoitsRobustFeaturesAndEsofuse.1)ITSImplifiesComplexComplextaskSwithitSmodernphpsyNtaxandToolSandToolSlikeBlikeforFront-Endandeloquentormquentormquentormforback-end.2)

Laravel的最新版本是什么?Laravel的最新版本是什么?Apr 24, 2025 pm 05:17 PM

Laravel10,releasedonFebruary7,2023,isthelatestversion.Itfeatures:1)Improvederrorhandlingwithanewreportmethodintheexceptionhandler,2)EnhancedsupportforPHP8.1featureslikeenums,and3)AnewLaravel\Promptspackageforinteractivecommand-lineprompts.

最新的Laravel版本如何简化开发?最新的Laravel版本如何简化开发?Apr 24, 2025 pm 05:01 PM

thelatestlaravelververversionenhancesdevelopmentwith:1)简化的inimpliticmodelbinding,2)增强EnhancedeloquentcapabibilitionswithNewqueryMethods和3)改善了supportorfortormodernphpfortornphpforternphpfeatureserslikenamedargenamedArgonedArgonsemandArgoctess,makecodingMoreftermeforefterMealiteFficeAndEnjoyaigaigaigaigaigaiganigaborabilyaboipaigyAndenjoyaigobyabory。

在哪里可以找到最新的Laravel版本的发行说明?在哪里可以找到最新的Laravel版本的发行说明?Apr 24, 2025 pm 04:53 PM

你可以在laravel.com/docs找到最新Laravel版本的发布说明。1)发布说明提供了新功能、错误修复和改进的详细信息。2)它们包含示例和解释,帮助理解新功能的应用。3)注意新功能的潜在复杂性和向后兼容性问题。4)定期审查发布说明可以保持更新并激发创新。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具