Alireza
Alireza

Reputation: 944

Laravel 5 says: "Unknown column 'user_id' in 'field list'", but I have 'author_id'

I have user and post models have this relation:

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

// User
public function articles() {
    return $this->hasMany('App\BlogPost');
}

In database I have "blog_posts" table with "author_id" field, but Laravel returns this error:
"Column not found: 1054 Unknown column 'user_id' in 'field list'".
What can I do?!

Upvotes: 1

Views: 2653

Answers (5)

chanafdo
chanafdo

Reputation: 5124

To fix the error pass the foreign key name as second argument for the articles relation defined in User model

// User model 
public function articles() {
    return $this->hasMany('App\BlogPost', 'author_id');
}

Explanation

In a hasMany or hasOne relation Laravel will use the class name to derive the foreign key if no foreign key name is passed as the second argument.

It will derive the name as follows.

  1. Get the class name
  2. Convert it into snake case
  3. Append _id

So in your case the articles relation defined under User will use a foreign key named user_id as you haven't provided a foreign key name which is not the correct foreign key.


In a belongsTo relation Laravel will use the relation name to derive the foreign key if no foreign key name is passed as the second parameter.

It will derive the name as follows.

  1. Get the relation name (function name or the 4th argument)
  2. Convert it into snake case
  3. Append _id

So in your case the author relation defined under BlogPost will correctly derive the foreign key named author_id

Upvotes: 4

BKF
BKF

Reputation: 1366

In blog_posts you should set user_id instead of author_id. As default, Laravel set tablename_id in relationship, in your case : user_id.

Upvotes: 0

Maurice Kuria
Maurice Kuria

Reputation: 59

Alireva ....That is how is supposed to be since the column author_id is in BlogPost table which is relating to a user table.

You are telling a user to look for the relation in BlogPost using a column in that table called author_id and not what you would expect that is user_id

Upvotes: 0

Alankar More
Alankar More

Reputation: 1115

If you have author_id as the column name in which you are saving the user id then rewrite the functions as below:

// BlogPost
public function author() {
    return $this->belongsTo('App\User','author_id');
}

Upvotes: 1

Gouda Elalfy
Gouda Elalfy

Reputation: 7023

when you don't match with Laravel naming standard you must pass your foreign key:

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

Upvotes: 1

Related Questions