2016-11-17 5 views
0

私のアプリでエラーが発生しましたが、それはうまくいくようですが、間違ったクエリを作成していますが、テーブルとモデルを正しく作成しています。複数の地域と業界/地域を選択できます。私のエラーは、次のとおりです。複数の地域と業種との関係でレコードを作成する

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'hjobs.region_user' doesn't exist (SQL: select `region_id` from `region_user` where `user_id` is null) 

モデルユーザー:

public function regionsToWork(){ 

     return $this->belongsToMany(Region::class); 
    } 

    public function industriesToWork(){ 
     return $this->belongsToMany(Industry::class); 
    } 

AuthController:

$user = new User(); 
$user->name = $data['name']; 
    ... 

$user->regionsToWork()->sync($data['region'], false); 
$user->industriesToWork()->sync($data['industry'], false); 
$user->save(); 

Tables DB: USER: 

    -id; 
    -email 
    ... 

user_industry: 

id; 
user_id; 
industry_id; 
user_region: 

id; 
user_id; 
region_id; 

移行user_region_table_creation

Schema::create('user_region', function($table){ 
      $table->increments('id'); 
      $table->integer('user_id')->unsigned(); 
      $table->foreign('user_id')->references('id')->on('users'); 

      $table->integer('region_id')->unsigned(); 
      $table->foreign('region_id')->references('id')->on('regions'); 
     }); 

user_industry_table_creation

Schema::create('user_industry', function($table){ 
      $table->increments('id'); 
      $table->integer('user_id')->unsigned(); 
      $table->foreign('user_id')->references('id')->on('users'); 

      $table->integer('industry_id')->unsigned(); 
      $table->foreign('industry_id')->references('id')->on('industries'); 
     }); 

答えて

1

ピボットテーブルの名前が予想通りのものではないようですが、user_regionではなくregion_userです。

あなたは手動でこのようなあなたのbelongsToMany方法でピボットテーブル名を指定することができます。

return $this->belongsToMany(Region::class, 'user_region'); 
+0

申し訳ありませんが、最後の答えのために、今私は、このエラーを与えている「SQLSTATE [23000]:整合性制約違反:1048列 ' (SQL: 'region_id'、 'user_id')の値(54、)に挿入してください)" –

+0

これは別の問題であるuser_idを渡さないことを意味します。ユーザーは使用するIDを持っていますか?明るい面では、今すぐ適切なテーブルを使用していることを意味します。 –

+0

あなたの権利私はちょうどsave()の後に - > syncメソッドを更新し、うまく動作します。 –

関連する問題