非自增ID等字段在creating事件中生成合理吗?

protected static function booted()
{
    static::creating(function ($replenish) {
        $replenish->code = (string) Str::uuid();
    });
}
让PHP再次伟大
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
最佳答案
declare(strict_types=1);

namespace App\Lib\Eloquent;

use Illuminate\Database\Eloquent\Model as BaseModel;

/**
 * @mixin \Illuminate\Database\Eloquent\Builder
 * @mixin \Illuminate\Database\Query\Builder
 * @package App\Lib\Eloquent
 */
abstract class Model extends BaseModel
{
    public $incrementing = false;

    protected static function booted(): void
    {
        // 创建时生成id
        static::creating(function (Model $model) {
            if (!$model->getIncrementing()) {
                $model->fill([$model->getKeyName() => snowflake()->id()]);
            }
        });
    }
}
2年前 评论
勇敢的心 (楼主) 2年前
YuliangLi (作者) 2年前
讨论数量: 6
陈先生

看起来是没什么问题的,看简单的逻辑是 非自增,非唯一的

2年前 评论
declare(strict_types=1);

namespace App\Lib\Eloquent;

use Illuminate\Database\Eloquent\Model as BaseModel;

/**
 * @mixin \Illuminate\Database\Eloquent\Builder
 * @mixin \Illuminate\Database\Query\Builder
 * @package App\Lib\Eloquent
 */
abstract class Model extends BaseModel
{
    public $incrementing = false;

    protected static function booted(): void
    {
        // 创建时生成id
        static::creating(function (Model $model) {
            if (!$model->getIncrementing()) {
                $model->fill([$model->getKeyName() => snowflake()->id()]);
            }
        });
    }
}
2年前 评论
勇敢的心 (楼主) 2年前
YuliangLi (作者) 2年前

建议使用模型提供的修改器

2年前 评论
勇敢的心 (楼主) 2年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!