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

protected static function booted()
{
    static::creating(function ($replenish) {
        $replenish->code = (string) Str::uuid();
    });
}
让PHP再次伟大
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案
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年前

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