tks.tman
tks.tman

Reputation: 414

Why is laravel changing the name of the column?

Here is the error I received:

"SQLSTATE[42S22]: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'user_user_id'. (SQL: insert into [APPLICATIONS] ([app_nm], [app_path], [app_readme_path], [app_manual_path], [is_url], [user_user_id]) values (TEST, uploads/2240120001.jpg, uploads/50225114.5-Data.pdf, uploads/9275171481557696855-FixedDeposits.docx, 0, 1))"

I have 3 Models:

User.php

public $primaryKey = 'user_id';

public function posts()
{
    return $this->hasMany('App\Post');
}

public function roles()
{
    return $this->belongsToMany('App\Role','USER_ROLE','user_id','role_id');
}

Role.php

public $timestamps = false;
public $primaryKey = 'role_id';

public function users()
{
    return $this->belongsTo('App\User');
}

Post.php

public $timestamps = false;
protected $table = 'APPLICATIONS';
protected $primaryKey='app_id';

public function user()
{
    return $this->belongsTo('App\User');
}

Laravel adds 'user_' to the 'user_id' column name resulting in the above error. I have checked the laravel 5.5 api to see if there is an additional parameter that needs to be supplied but that doesn't seem to be the case.

What would cause this concatenation and how do I fix it?

Upvotes: 1

Views: 1151

Answers (1)

Jason
Jason

Reputation: 3030

You haven't defined the user relationship on Post properly. By default, if you don't explicitly add the related tables, Eloquent will infer the name of the foreign key field from the table name, and the primary key name.

In your case, the relationship table name is user and the primary key of that table you have defined as user_id. Because of this, it assumes the foreign key in your APPLICATIONS table to be user_user_id.

To address this, explicity name your foreign and other table ids in your relationship:

public function user()
{
    return $this->belongsTo('App\User', 'user_id', 'user_id');
}

The second parameter in the above code will be your foreign key on the APPLICATIONS table (since you haven't explicitly said what is meant to be)

Upvotes: 2

Related Questions