EloquentでStringなプリマリーキーの実装。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
class Post extends Model
{
// primary key column, default id.
\!h protected $primaryKey = 'uuid';
// primary key type, default int.
\!h protected $keyType = 'string';
// primary key auto incrementing, default true.
\!h public $incrementing = false;
// constructor
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
// generate uuid
$this->attributes['uuid'] = Uuid::uuid4()->toString();
}
}
property | default value | change | |
---|---|---|---|
protected | $primaryKey | id | code |
protected | $keyType | int | string |
public | $incrementing | true | false |