laravel uuid 未在查询中显示

2024-02-20

我有一个 postgres 数据库表,它使用 uuid 作为主键,通过webpatser/laravel-uuid包,以及“可读”的网络 ID 通过温克拉/哈希德.

当我查询数据库时,如果我dd()响应中,我看到了完整的 UUID,但如果我只是return,我得到一个整数。

假设我忽略了一些明显的事情,所以:

移民

$table->uuid('id');
$table->string('web_id');

$table->primary('id');

Model

public function store()
{
    $data = [
        'id' => Uuid::generate(4)->string,
        'web_id' => Hashids::encode(mt_rand(1,1000000)),

我假设当数据转换为 json 时会发生一些事情,但我不确定从哪里开始解决这个问题......

我也在工匠修补匠中看到了同样的行为,fwiw:

 >>> $result = App\Model::firstOrFail() 
 => App\Model {#675
     id: "587bb487-881d-417e-8960-fbecaa3b270b",
     web_id: "Mxqv4LYP",
     created_at: "2016-01-25 15:52:25+00",
     updated_at: "2016-01-25 15:52:25+00",
    }

 >>> $result->id
 => 587

Eloquent 假设主键(即named id默认情况下 https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L56) 是一个整数,并将其转换为int默认情况下在getCasts https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2821 method:

public function getCasts()
{
    if ($this->incrementing) {
        return array_merge([
            $this->getKeyName() => 'int',
        ], $this->casts);
    }
    return $this->casts;
}

可以通过将其添加到模型中来指定主键不自动递增来覆盖它:

$incrementing = false;

或者通过投射id列至string in the $casts模型的属性,如下所示:

protected $casts = [
    'id' => 'string'
]

如中所述雄辩:属性铸造 https://laravel.com/docs/master/eloquent-mutators#attribute-casting文档。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

laravel uuid 未在查询中显示 的相关文章

随机推荐