Laravel 模型:启动特征和模型

Laravel Model: boot on trait and model

我有一些 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() 方法?

Uuids 中的 boot 函数将不会被触发,为了解决这个问题,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";
  }
}