У меня есть несколько моделей Laravel, использующих следующую черту, которая вызывает метод загрузки модели:
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait Uuids
{
/**
* Boot function from Laravel.
*/
protected static function boot()
{
parent::boot();
static::creating(function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
if ($model->consecutive) {
$model->consecutive = $model->max("consecutive") + 1;
}
}
});
}
/**
* Get the value indicating whether the IDs are incrementing.
*
* @return bool
*/
public function getIncrementing()
{
return false;
}
/**
* Get the auto-incrementing key type.
*
* @return string
*/
public function getKeyType()
{
return "string";
}
}
Но на одной из моделей у меня есть consecutiveстолбец, который мне нужно автоинкрементировать, и я делал это с помощью функции загрузки в модели:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Order extends Model
{
use HasFactory, Uuids;
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->consecutive = $model->max("consecutive") + 1;
});
}
}
Проблема в том, что вызывается только черта boot(). Есть ли другой способ заполнить consecutiveстолбец моей модели или вызвать boot()метод в обоих файлах?
Решение проблемы
Функция bootв Uuidsне будет запущена, и чтобы решить эту проблему, в Laravel есть замечательная скрытая функция, которая говорит, что если имя функции в вашей черте было bootYourTraitName, оно будет запущено с функцией модели загрузки, например так
<?php
namespace App\Traits;
use Illuminate\Support\Str;
trait Uuids
{
/**
* Boot function from Laravel.
*/
protected static function bootUuids()
{
static::creating(function ($model) {
if (empty($model->{$model->getKeyName()})) {
$model->{$model->getKeyName()} = Str::uuid()->toString();
if ($model->consecutive) {
$model->consecutive = $model->max("consecutive") + 1;
}
}
});
}
/**
* Get the value indicating whether the IDs are incrementing.
*
* @return bool
*/
public function getIncrementing()
{
return false;
}
/**
* Get the auto-incrementing key type.
*
* @return string
*/
public function getKeyType()
{
return "string";
}
}
Комментариев нет:
Отправить комментарий