0
votes

I am working on a Laravel project and I have an issue when trying to save data. Here is the error message that i get:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'user_user_id' in 'field list' (SQL: insert into link_user_accounts (account_id, user_user_id, updated_at, created_at) values (1, 6, 2019-12-30 20:32:54, 2019-12-30 20:32:54))

I am expecting to see the following insert statement:

insert into link_user_account(account_id, user_id) values(val1, val2)

But in this case the user_id is somehow being renamed to user_user_id

Models

  1. Account
  2. User
  3. LinkAccountUser

UserController:

    public function store(Request $request)
    {
       $account_id = Auth::user()->account_id;

       $user = new User();

       $user->first_name = $request->first_name;
       $user->last_name = $request->last_name;
       $user->practice_number = $request->practice_number;
       $user->save();

       $user_account = new LinkUserAccount();
       $user_account->account_id = $account_id;

       $user->link_user_account()->save($user_account);

User model relationship

public function link_user_account()
{
    return $this->hasOne(LinkUserAccount::class);
}

Account model relationship

public function link_user_account()
{
    return $this->hasOne(LinkUserAccount::class);
}

LinkUserAccount relationship

public function user()
{
    return $this->belongsTo(User::class, 'account_id', 'user_id');
}

public function account()
{
    return $this->belongsTo(Account::class, 'account_id');
}
2

2 Answers

1
votes

On the LinkUserAccount model, remove the user_id for the other key:

public function user()
{
     return $this->belongsTo(User::class); // It will automatically go to id on User
}

The way you had it, with user_id in the other key parameter, it was telling Laravel to look for user_id on the User model, instead of id, which in combination with the inclusion of the account_id as the FK and the slightly unusual naming convention (LinkUserAccount), probably confused it to the point of looking for user_user_id.

0
votes

This happens because Eloquent adds user_ to the id. In my case I solved this by changing the primary key of my table simply by calling it 'id'