我有以下用于创建地址表的模式:
Schema::create('addresses', function (Blueprint $table) {
$table->string('id')->index();
$table->string('street', 100);
$table->integer('number', 5);
$table->string('addition', 10);
$table->string('postal_code', 7);
$table->string('place', 45);
$table->string('country', 45);
$table->timestamps();
$table->softDeletes();
});
出于安全原因,"id"是随机生成的唯一字符串,而不是自动递增的整数。
只有一个问题:Laravel使列"number"是唯一的,因为它是唯一一个数据类型为integer的列。我们希望列"id"作为主键和唯一键。
我们也尝试过这个:
$table->primary('id')->index();
$table->uuid('id')->index();
$table->string('id')->primary()->index();
我仍然收到这个错误:
完整性约束冲突:19 UNIQUE约束失败:
地址编号
这对我有效:
Schema::create('addresses', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->integer('number', false);
});
我遇到了这个问题。查看这篇文章:http://garrettstjohn.com/article/using-uuids-laravel-eloquent-orm/
事实上,Laravel"说"他们支持UUID,但他们真的需要帮助。
你的模式会起作用,但为了确定,我使用它如下:
$table->primary('id');
在使用了本文提供的示例之后,您应该有类似的东西(这是我的用户模型):
<?php
namespace App;
use IlluminateFoundationAuthUser as Authenticatable;
use IlluminateDatabaseEloquentSoftDeletes;
class User extends Authenticatable
{
// UuidForKey is a custom trait added in the app folder
use SoftDeletes, UuidForKey;
// This disabled the auto-incrementing
public $incrementing = false;
// Make sure id is set as primary
protected $primaryKey = "id";
// Makes sure that the id is a string and not an integer
protected $casts = [
'id' => 'string',
];
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'firstname',
'lastname',
'email',
'password',
'role',
'active',
];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}