1
votes

I try to insert some data to the new table that I have create but laravel choose wrong reverse table. Instead of job_contract get contract_job.

QueryException in Connection.php line 636: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'job.contract_job' doesn't exist (SQL: insert into contract_job (contract_id, job_id) values (2, 4))

I am new in laravel. Is anyone know the way that laravel defines the names of tables

3

3 Answers

2
votes

I am not sure about what the Model name of your related php file is.

Usually, the table would be like

if your model name isUser the table name should be users !

For tables like customer_details , the model name should be CustomerDetail

But you can also select a particular table with the model using

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * The table associated with the model.
     * 
     * @var string
     */
    protected $table = 'my_flights';
}

In this example, you can see that the table name by default should be flights but you can change it to whatever you want like this !

1
votes

A way to fix this is to tell the Model wich table to use (Put in your model):

protected $table = 'job_contract';

This way you force the Model to use that table and not some other table See more here

0
votes

A quote about the relation table:

The role_user table is derived from the alphabetical order of the related model names, and contains the user_id and role_id columns.

In your case it would be contract_job with contract_id and job_id.

And another quote:

However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method:

return $this->belongsToMany('App\Role', 'user_roles');

So I guess you only need to pass the correct table name as second param to your belongsToMany method(s) like this:

//in your Contract model
return $this->belongsToMany('App\Job', 'job_contract');

and

//in your Job model
return $this->belongsToMany('App\Contract', 'job_contract');

Quotes from Laravel docs