V
V
vism2017-09-06 20:20:10
Laravel
vism, 2017-09-06 20:20:10

How to do pessimistic lock in laravel?

This code can sometimes receive many requests in a row and the code does not have time to work out.
When changing fields, the current record is *softly* deleted and a new one is created.

try {
    DB::beginTransaction();

    $model = $this->model
        ->where('ident_id', '=', $model->ident_id)
        ->whereNull('deleted_at')
        ->orderBy('created_at', 'desc')
        ->withTrashed()
        ->sharedLock()
        ->first();

    $fieldType = $this->getColType($table, $fieldName);
    if ($fieldType == "decimal" && strpos($fieldValue, ",") !== false) {
        $fieldValue = str_replace(",", ".", $fieldValue);
    }

    $model = $model->fill([$fieldName => $fieldValue])->saveAsNew();
    DB::commit();
} catch (Exception $ex) {
    DB::rollback();
    dd($ex);
}

public function saveAsNew()
{
    if ($this->isDirty([
        'name',
        'ek',
        'vk',
        'category_id',
        'manufacturers_id',
        'size',
//            'vendor_code',
        'comfort_grade',
        'color',
        'option1',
    ])
    ) {
        /** @var Product $newModel */
        $newModel = $this->replicate();
        $newModel->original_id = $this->id;
        $originals = $this->getOriginal();
        if ($newModel->save()) {
            $this->setRawAttributes($originals);
            $this->delete();

            return $newModel;
        } else {
            return false;
        }
    }
    $this->save();
    return $this;
}

In this case, there is a duplication of records.
I need the next model select to occur only after the end of the transaction.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question