【问题标题】:laravel uuid not showing in querylaravel uuid 未在查询中显示
【发布时间】:2016-01-25 16:44:42
【问题描述】:

我有一个 postgres 数据库表,它使用 uuid 作为其主键,通过 webpatser/laravel-uuid 包,以及通过 vinkla/hashids 的“可读”网络 ID >.

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

假设我忽略了一些明显的东西,所以:

迁移

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

$table->primary('id');

型号

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

【问题讨论】:

  • 你的id字段在数据库中的类型是什么,长度是多少?
  • 我正在使用 postgres,Postico 只是将其报告为 'uuid' 类型,如果这有帮助的话。
  • 可能会尝试将结果转换为数组->toArray()并制作dd();
  • 谢谢 - 所以,在 tinker 中,$resultdd($result)'id' => (uuid...),而 $result->toArray()dd($result->toArray()) 都给 'id' => (integer...)

标签: php postgresql laravel eloquent uuid


【解决方案1】:

Eloquent 假设主键(即named id by default)是一个整数,并在getCasts 方法中默认将其转换为int

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

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

$incrementing = false;

或者通过将id 列转换为模型的$casts 属性中的string,如下所示:

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

Eloquent: Attribute Casting 文档中所述。

【讨论】:

  • 啊哈!感谢您的更新 - 现在非常有意义!
  • 我已经为未来的读者更新了你的答案,包括解释为什么 id 被自动转换为 int
  • 我在答案中发布了第二个(更简单的)解决方案,它也可以解决问题,因为它使getCasts 中的条件为假,因此它避免了id 被强制转换为@首先是 987654337@。
  • 你也可以覆盖模型的protected $keyType = 'string';属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
相关资源
最近更新 更多