You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

cyrildewit/eloquent-viewable适配UUID:如何修改迁移文件

适配UUID模型的迁移修改方案

默认迁移里的morphs('viewable')方法会生成无符号大整数类型的viewable_id字段,但你的listings表用UUID作为主键(字符串类型),类型不匹配导致无法正常存储浏览记录。需要修改迁移文件中的形态关联字段定义:

修改后的迁移代码

public function up()
{
    $this->schema->create($this->table, function (Blueprint $table) {
        $table->bigIncrements('id');
        // 替换原有的morphs方法为uuidMorphs
        $table->uuidMorphs('viewable');
        $table->text('visitor')->nullable();
        $table->string('collection')->nullable();
        $table->timestamp('viewed_at')->useCurrent();
    });
}

手动替代方案(如果uuidMorphs不适用)

如果需要更精细的控制,可以手动定义两个字段并添加联合索引:

public function up()
{
    $this->schema->create($this->table, function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->uuid('viewable_id');
        $table->string('viewable_type');
        $table->index(['viewable_id', 'viewable_type']);
        $table->text('visitor')->nullable();
        $table->string('collection')->nullable();
        $table->timestamp('viewed_at')->useCurrent();
    });
}

配套模型设置

确保你的Listing模型正确配置主键类型并使用Viewable trait:

class Listing extends Model
{
    use \CyrildeWit\EloquentViewable\Viewable;

    protected $primaryKey = 'id';
    public $incrementing = false;
    protected $keyType = 'string';
}

注意事项

如果已经执行过默认迁移,需要先回滚迁移(php artisan migrate:rollback),再运行修改后的迁移。

内容的提问来源于stack exchange,提问作者blackbeaches

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 16:03:21