laravel uuid not showing in query

为君一笑 提交于 2019-12-24 01:01:27

问题


I've a postgres database table that uses uuid's as its primary key, via the webpatser/laravel-uuid package, and 'readable' web ids via vinkla/hashids.

When I query the database, if I dd() the response, I see the UUID in full, but if I simply return, I instead get an integer.

Presume I've overlooking something obvious, so:

Migration

$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)),

I'm assuming something happens when the data is cast to json, but I'm not sure where'd I'd begin to tackle this...

I also see the same behaviour in artisan tinker, 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

回答1:


Eloquent makes the assumption that the primary key (which is named id by default) is an integer, and it casts it to int by default in the getCasts method:

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

This can be overwritten by specifying that the primary key is not auto incrementing by adding this to your model:

$incrementing = false;

Or by casting the id column to string in the $casts property of the model, like so:

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

As described in the Eloquent: Attribute Casting documentation.



来源:https://stackoverflow.com/questions/34997767/laravel-uuid-not-showing-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!