Laravel lararvel uuid作为主键
我正在尝试将uuid设置为Laravel模型中的主键。我已经在我的模型中设置了一个启动方法,这样我就不必每次创建和保存模型时都手动创建它。我有一个控制器,它只创建模型并将其保存在数据库中 它正确地保存在数据库中,但当控制器返回id值时,它总是返回0。如何使它实际返回它在数据库中创建的值 模型 控制器 您需要将keyType更改为string,并将incrementing更改为false。因为它不是递增的Laravel lararvel uuid作为主键,laravel,uuid,laravel-events,Laravel,Uuid,Laravel Events,我正在尝试将uuid设置为Laravel模型中的主键。我已经在我的模型中设置了一个启动方法,这样我就不必每次创建和保存模型时都手动创建它。我有一个控制器,它只创建模型并将其保存在数据库中 它正确地保存在数据库中,但当控制器返回id值时,它总是返回0。如何使它实际返回它在数据库中创建的值 模型 控制器 您需要将keyType更改为string,并将incrementing更改为false。因为它不是递增的 public $incrementing = false; protected $keyTy
public $incrementing = false;
protected $keyType = 'string';
此外,我有一个特点,我只是添加到那些有UUID键的模型中。这是非常灵活的。这源于,我对它进行了一些小的调整,以解决我在集中使用它时发现的问题
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';
}
}
希望这有帮助
public $incrementing = false;
protected $keyType = 'string';
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';
}
}