2016-04-13 5 views
8

によって一意の列を作成します。セキュリティ上の理由からLaravel 5.2データベース方式は、私がアドレステーブルを作成するための次のスキーマきたこと自己

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」は、代わ​​りにANの生成されたランダムかつ一意の文字列であります自動増分整数。

ただ1つの問題:Laravelは、データ型がintegerの唯一の列であるため、列 'number'を一意にします。私たちは、カラム 'id'をプライマリで一意のキーとしたい。

我々はまた、この試みた:

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

を私はまだ、このエラーを取得しています:

Integrity constraint violation: 19 UNIQUE constraint failed:
addresses.number

+0

を私はここに何か他のものについてコメントするつもりです - あなたは、ランダムな世代を使用していますセキュリティ上の理由からauto_incrementの代わりに独自の文字列をエリートしました。その理由は何ですか?数値IDを公開したくない場合は、コード化されたIDを配信するか、暗号化してbase64_encodeして配信してください。そうでなければ、非常に悪い時を過ごすことになり、データがいつ成長するのかを学びます。 – Mjh

答えて

3

これが私の仕事:

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

LaravelがIDと番号の2つの主キーを作成したので、これはほぼ成功しました。そこで$ table-> integer( 'number'、5)を$ table-> integer( 'number'、false)に変更しました。 2番目のパラメータは 'auto increment'を無効にしました。 – Marten

+0

興味深い...あなたの答えに合わせて私の答えを編集しました。私はチェックしたと言っていますが、Laravelは何らかの理由で – PeterTheLobster

0

私はこの正確な問題を抱えていました。この記事をチェックしてください:http://garrettstjohn.com/article/using-uuids-laravel-eloquent-orm/

Laravelは「彼らはUUIDをサポートしていますが、本当に救いの手を必要としています。あなたのスキーマが、私はこのようにそれを使用し、動作しますが、念のために

$table->primary('id'); 

記事の提供例を使用した後、あなたはこれに似た何かを持っている必要があります(これは私のUserモデルです):

<?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', 
    ]; 
} 
関連する問題