Heim > PHP-Framework > Laravel > Hauptteil

Implementierung des optimistischen Sperrens im Laravel Eloquent-Modell

藏色散人
Freigeben: 2023-04-21 15:53:05
nach vorne
1021 Leute haben es durchsucht

Dieser Artikel bringt Ihnen relevantes Wissen über Laravel. Er stellt Ihnen hauptsächlich die Implementierung des optimistischen Sperrens im Laravel Eloquent-Modell vor. Ich hoffe, dass es für Sie hilfreich ist.

Erstellen Sie OptimisticLockTrait.php im Verzeichnis app/Utils/Traits. Der Code lautet wie folgt:

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;
    }}
Nach dem Login kopieren

Anweisungen zur Verwendung von Optimistic Lock

1. Verwenden Sie es im Modell (Models) oder in der übergeordneten Modellklasse

/**
* 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;}
Nach dem Login kopieren

2. Verwenden Sie die Methode:

 $ord = Order::find(1);
 $ord->payment_status = 1;
 if(!$model->setOptimistic(['payment_status' => 0]))->save())
   throws new Exception('订单已付过款了');
Nach dem Login kopieren

Oder verwenden Sie die ursprüngliche SQL-Methode:

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

Wenn dasselbe Objekt mehrere Aktualisierungen umfasst, können Sie die Sperrbedingung löschen.

$ord->clearOptimistic();
Nach dem Login kopieren

Das Obige ist die Implementierungsmethode der optimistischen Sperre Wird häufig verwendet und ist in der tatsächlichen Entwicklung erforderlich.

Empfohlenes Lernen: „Laravel-Video-Tutorial

Das obige ist der detaillierte Inhalt vonImplementierung des optimistischen Sperrens im Laravel Eloquent-Modell. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Verwandte Etiketten:
Quelle:learnku.com
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!