Jaz*_*zzy 5 mysql uuid laravel eloquent laravel-4
我试图使用Laravel 4将UUID用作主键.
没有找到关于这个主题的太多信息我决定在MySQL中使用一个触发器来设置id列,其值为UUID()on insert.
根据我的阅读,我需要在模型中设置var
public $incrementing = false;
Run Code Online (Sandbox Code Playgroud)
在我的迁移文件中,每个表都有这样的内容:
//set default id to UUID, requires thread_stack in my.cnf to be 196k
function makeTrigger($tableName)
{
DB::unprepared('CREATE TRIGGER '.$tableName.'_trigger_id BEFORE INSERT ON '.$tableName.' FOR EACH ROW SET NEW.id = UUID()');
}
$tableName = 'sites';
Schema::create($tableName, function($table)
{
$table->string('id', 36)->primary();
$table->string('name', 50);
$table->string('development_url', 50);
$table->string('production_url', 50);
$table->boolean('launched')->default(0);
$table->string('test');
$table->timestamps();
$table->softDeletes();
});
makeTrigger($tableName);
Run Code Online (Sandbox Code Playgroud)
虽然我可以插入具有UUID的这样的记录,但如果在模型中设置了$ incrementing = false,则无法返回ID.
如果我删除该var并且我使用的是UUID,则返回的id为0.如果我在迁移文件中使用增量('id'),则返回真实的id.
我正在构建一个在规范中使用UUID的应用程序,因此我想知道这是否可以在Laravel 4中使用.
如果我无法使用该ID
$user = User::create($userdata);
return $user->id;
Run Code Online (Sandbox Code Playgroud)
那么如何将id用于关系呢?(使用$ user-> save();)的相同问题
根据我的理解,Eloquent期待auto_increment回归,但似乎应该有办法让任何id回来.
为什么这不起作用?
任何有关这一领域的见解将不胜感激,因为我似乎无法找到关于这个主题的任何真实文档.
我通过使用creating模型上的事件在模型保存时添加新的UUID来解决这个问题.您也可以在packagist上找到我的解决方案.
class BaseModel extends Eloquent {
/**
* Indicates if the IDs are auto-incrementing.
*
* @var bool
*/
public $incrementing = false;
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
static::creating(function($model)
{
$model->{$model->getKeyName()} = (string)$model->generateNewId();
});
}
/**
* Get a new version 4 (random) UUID.
*
* @return \Rhumsaa\Uuid\Uuid
*/
public function generateNewId()
{
return \Rhumsaa\Uuid\Uuid::uuid4();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1937 次 |
| 最近记录: |