我正在尝试将 uuid 设置为 Laravel 模型中的主键。我已经完成了在我的模型中设置启动方法的工作here https://github.com/webpatser/laravel-uuid所以我不必每次想要创建和保存模型时都手动创建它。我有一个控制器,它只创建模型并将其保存在数据库中。
它已正确保存在数据库中,但当控制器返回时,id 的值始终返回0
。我怎样才能让它真正返回它在数据库中创建的值?
Model
class UserPersona extends Model
{
protected $guarded = [];
protected $casts = [
'id' => 'string'
];
/**
* Setup model event hooks
*/
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$uuid = Uuid::uuid4();
$model->id = $uuid->toString();
});
}
}
控制器
class UserPersonaController extends Controller
{
public function new(Request $request)
{
return UserPersona::create();
}
}
您需要更改keyType
to string
and incrementing
to false
。因为它没有增加。
public $incrementing = false;
protected $keyType = 'string';
另外我有一个trait
我只是将其添加到那些具有 UUID 键的模型中。这非常灵活。这最初来自https://garrettstjohn.com/articles/using-uuid-laravel-eloquent-orm/ https://garrettstjohn.com/articles/using-uuid-laravel-eloquent-orm/针对我在密集使用过程中发现的问题,我对其进行了一些小的调整。
use Illuminate\Database\Eloquent\Model;
use Ramsey\Uuid\Uuid;
/**
* Class Uuid.
* Manages the usage of creating UUID values for primary keys. Drop into your models as
* per normal to use this functionality. Works right out of the box.
* Taken from: http://garrettstjohn.com/entry/using-uuids-laravel-eloquent-orm/
*/
trait UuidForKey
{
/**
* The "booting" method of the model.
*/
public static function bootUuidForKey()
{
static::retrieved(function (Model $model) {
$model->incrementing = false; // this is used after instance is loaded from DB
});
static::creating(function (Model $model) {
$model->incrementing = false; // this is used for new instances
if (empty($model->{$model->getKeyName()})) { // if it's not empty, then we want to use a specific id
$model->{$model->getKeyName()} = (string)Uuid::uuid4();
}
});
}
public function initializeUuidForKey()
{
$this->keyType = 'string';
}
}
希望这可以帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)