tae*_*kni 2 php postgresql uuid laravel eloquent
我有一个postgres数据库表,它使用uuid作为主键,通过webpatser/laravel-uuid包,通过vinkla/hashids使用 '可读'web ID .
当我查询数据库时,如果我dd()响应,我完全看到UUID,但如果我只是返回,我会得到一个整数.
假设我忽略了一些明显的东西,所以:
移民
$table->uuid('id');
$table->string('web_id');
$table->primary('id');
Run Code Online (Sandbox Code Playgroud)
模型
public function store()
{
$data = [
'id' => Uuid::generate(4)->string,
'web_id' => Hashids::encode(mt_rand(1,1000000)),
Run Code Online (Sandbox Code Playgroud)
我假设当数据被转换为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
Run Code Online (Sandbox Code Playgroud)
tae*_*kni 12
Eloquent假设主键(默认命名id)是一个整数,并且int默认情况下将其强制转换为getCasts方法:
public function getCasts()
{
if ($this->incrementing) {
return array_merge([
$this->getKeyName() => 'int',
], $this->casts);
}
return $this->casts;
}
Run Code Online (Sandbox Code Playgroud)
这可以通过将主键添加到模型中来指定主键不自动递增来覆盖:
$incrementing = false;
Run Code Online (Sandbox Code Playgroud)
或者通过将id列转换为模型string的$casts属性,如下所示:
protected $casts = [
'id' => 'string'
]
Run Code Online (Sandbox Code Playgroud)
如Eloquent:Attribute Casting文档中所述.
小智 5
在 laravel 8 中我必须设置
public $incrementing = false;
Run Code Online (Sandbox Code Playgroud)
进入模型。
| 归档时间: |
|
| 查看次数: |
1573 次 |
| 最近记录: |