Laravel 外键列命名约定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35539216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
laravel foreign key column naming convention
提问by amin
I have a LessonGroup
model and its tabel name is lesson_groups
. if i want to use this table id
in another tabel as a foreign key, what column name should i select that Laravel could distinguish it automatically as a foreign keyto lesson_group
table?
我有一个LessonGroup
模型,它的表格名称是lesson_groups
. 如果我想使用此表id
在另一个TABEL作为外键,我应该选择什么样的列名Laravel可以自动识别它作为一个外键到lesson_group
表?
lesson_groups
id
name
-----------------------------------------
fields
id
//foreign key to lesson_groups(what should be the name of this column?)
name
回答by Bogdan
Below is an excerpt from the Laravel Eloquent Documentation:
以下是Laravel Eloquent 文档的摘录:
Eloquent determines the default foreign key name by examining the name of the relationship methodand suffixing the method name with
_id
.
Eloquent 通过检查关系方法的名称并为方法名称添加后缀来确定默认外键名称
_id
。
So for the naming convention to work seamlessly, you would need to have a relation like this defined in your Field
model:
因此,为了让命名约定无缝工作,您需要在Field
模型中定义这样的关系:
public function lesson_group()
{
return $this->hasOne('App\LessonGroup');
}
回答by Azmeer
The issue here is Laravel pluralize the table names from Model name. eg: LessonGroup
model will make the table lesson_groups
(via Migration).
So the proper foreign key field name would be lesson_group_id
?
这里的问题是 Laravel 将模型名称中的表名称复数化。例如:LessonGroup
模型将制作表格lesson_groups
(通过迁移)。那么正确的外键字段名称是lesson_group_id
?
回答by Brandon Smith
A good naming convention is the model name with underscores, followed by the id with an underscore. For example, FishingBoat would be fishing_boat_id.
一个好的命名约定是带下划线的模型名称,后跟带下划线的 id。例如,FishingBoat 将是fishing_boat_id。
Laravel will automatically assume that the foreign and/or local keys are in this format, unless defined otherwise.
Laravel 会自动假定外键和/或本地键采用这种格式,除非另有定义。