2017-07-21 3 views
1

の関係*

ユーザーテーブル:

Schema::create('users', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('firstname'); 
     $table->string('surename'); 
     $table->string('address')->nullable(); 
     $table->string('city')->nullable(); 
     $table->string('country')->nullable(); 
     $table->string('postcode')->nullable(); 
     $table->string('email')->unique(); 
     $table->string('password'); 
     $table->rememberToken(); 
     $table->timestamps(); 
    }); 

Setting_typeテーブル:

Schema::create('setting_types', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name'); 
     $table->timestamps(); 
    }); 

設定表:

Schema::create('settings', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('value'); 
     $table->timestamps(); 
    }); 

Setting_type_userテーブル:

Schema::create('setting_type_user', function (Blueprint $table) { 
     $table->integer('user_id')->unsigned(); 
     $table->integer('type_id')->unsigned(); 
     $table->integer('setting_id')->unsigned(); 
     $table->foreign('user_id')->references('id')->on('users'); 
     $table->foreign('type_id')->references('id')->on('setting_types'); 
     $table->foreign('setting_id')->references('id')->on('settings'); 
     $table->timestamps(); 
    }); 

これは私が取得したい結果である:

{"id":1,"value":"578943205.jpg","created_at":"2017-07-18 00:00:00","updated_at":null,"pivot":{"setting_id":1,"user_id":1,"type_id":1}} 

答えて

0

それは多くのものに依存しますが、あなたはここにmany-to-many関係を使用したいように見えます。その後、両方のUserSettingTypeモデルでbelongsToMany()関係を定義

$table->foreign('user_id')->references('id')->on('users'); 
$table->foreign('type_id')->references('id')->on('setting_types'); 

$table->unsignedInteger('user_id'); 
$table->unsignedInteger('type_id'); 

また、テーブルにforeign key constraintsを追加することをお勧めします:

まず、settings pibotテーブルにそれを変更します。命名規則に従わないので、外部キーを手動で定義する必要があります。

public function settingTypes() 
{ 
    return $this->belongsToMany('App\SettingType', 'settings', 'user_id', 'type_id'); 
} 

そしてSettingTypeモデルで:Userモデルで

public function users() 
{ 
    return $this->belongsToMany('App\User', 'settings', 'type_id', 'user_id'); 
} 
+0

SQLSTATE [42000]:構文エラーまたはアクセス違反:1066ユニークでないテーブル/別名: '設定'(SQL:選択して ' 'settings' .'id''を' settings'.'id''として 'settings'を' pivot_user_id'として 'settings'.user_id'を' settings'.id'として 'settings'内部結合' settings'から 'pivot_id'として' 'id'は' settings'.user_id'がnullで 'id' = 1の場合1) – Marco

+0

@Marcoこの問題を解決するには、エラーが発生したときに実行しているコードを投稿する必要があります。 –

+0

私は、あなたが投稿した例のようにすべてを行っています。テスト目的のために、私はメソッド設定を作成しました:public function setting(){$ user = Auth :: user(); – Marco