[英]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: 在数据库中,我有带有“ author_id”字段的“ blog_posts”表,但是Laravel返回此错误:
"Column not found: 1054 Unknown column 'user_id' in 'field list'". “找不到列:1054'字段列表'中的未知列'user_id'”。
What can I do?! 我能做什么?!
To fix the error pass the foreign key name as second argument for the articles
relation defined in User
model 要解决该错误,请将外键名称作为
User
模型中定义的articles
关系的第二个参数传递
// 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. 在
hasMany
或hasOne
关系中,如果没有将外键名称作为第二个参数传递,Laravel将使用类名称来派生外键。
It will derive the name as follows. 它将得出如下名称。
_id
_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. 因此,在您的情况下,“
User
下定义的articles
关系将使用名为user_id
的外键,因为您没有提供不是正确外键的外键名。
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. 如果没有将任何外键名称作为第二个参数传递,那么在
belongsTo
关系中,Laravel将使用关系名称来导出外键。
It will derive the name as follows. 它将得出如下名称。
_id
_id
So in your case the author
relation defined under BlogPost
will correctly derive the foreign key named author_id
因此,在您的情况下,在
BlogPost
下定义的author
关系将正确派生名为author_id
的外键
when you don't match with Laravel naming standard you must pass your foreign key: 当您与Laravel命名标准不匹配时,必须传递外键:
public function author() {
return $this->belongsTo('App\User', 'foreign_key');
}
If you have author_id as the column name in which you are saving the user id then rewrite the functions as below: 如果将author_id作为要保存用户ID的列名,请重写以下函数:
// BlogPost
public function author() {
return $this->belongsTo('App\User','author_id');
}
Alireva ....That is how is supposed to be since the column author_id is in BlogPost table which is relating to a user table. Alireva...。那是应该的,因为author_id列位于与用户表有关的BlogPost表中。
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 您正在告诉用户使用该表中称为author_id的列而不是您希望的user_id来在BlogPost中查找关系。
In blog_posts you should set user_id instead of author_id. 在blog_posts中,您应该设置user_id而不是author_id。 As default, Laravel set tablename_id in relationship, in your case : user_id.
默认情况下,Laravel在您的情况下将tablename_id设置为关系:user_id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.