Laravel 5.2数据库方案自动创建唯一列

8

我有以下方案来创建地址表:

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”唯一,因为它是唯一具有整数数据类型的列。我们希望将列“id”作为主键和唯一键。

我们也尝试过这样做:

$table->primary('id')->index();
$table->uuid('id')->index();
$table->string('id')->primary()->index();

我仍然遇到这个错误:
完整性约束冲突:19个唯一性约束失败:
地址.number

我要在这里评论另一件事情 - 你使用随机生成的唯一字符串而不是自动递增,因为出于安全原因 - 这些原因是什么?如果您不想公开数字ID,为什么不提供编码或加密后的ID,base64_encode它并提供那个?否则,当您的数据增长时,您将会遇到非常非常糟糕的情况,并且您将会了解其中的原因。 - Mjh
2个回答

3
这对我有用:

这对我有用:

Schema::create('addresses', function (Blueprint $table) {
      $table->uuid('id')->primary();
      $table->integer('number', false);
  });

这个几乎起作用了,但我仍然有一个错误,因为Laravel创建了两个主键:id和number。所以我将$table->integer('number', 5)更改为$table->integer('number', false); 第二个参数禁用了“自动增量”。 - Marten
有趣...我编辑了我的答案以匹配你的...虽然我必须说,我检查了一下,Laravel没有为我将数字列设置为主键,原因不明。 - PeterTheLobster

0

我曾经遇到过完全相同的问题。看看这篇文章:http://garrettstjohn.com/article/using-uuids-laravel-eloquent-orm/

基本上,Laravel “说”他们支持 UUID,但实际上他们需要帮助。

你的模式可以正常工作,但为了确保,我将其用作:

$table->primary('id');

在使用本文提供的示例后,您应该拥有类似于以下内容(这是我的用户模型):

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;

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',
    ];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接