Marco Santos Marco Santos - 23 days ago 6
PHP Question

Creating records with relations between multiple regions and industries

im having a error with my app, it looks averything fine, but is creating a wrong query, but i have my tables and models right, basically i have a registration of a user that can select more than one regions and industry/area. My error is:

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)


Model User:

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;


Migrations 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');
});

Answer

It looks like the pivot table name is different than what it's expecting, region_user as opposed to user_region.

You can manually specify the pivot table name in your belongsToMany method like this:

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