eloquent如何识别表格? [英] How does eloquent recognize tables?
问题描述
我很好奇 eloquent 如何知道它应该通过运行 $ php artisan tinker
来保存我们给它的记录.我实际上不记得设置了这样一个选项.
I am curious about how eloquent knows in which table it should save the records we give it by running $ php artisan tinker
. I do not actually remember setting so an option.
推荐答案
在 Laravel
中使用 Eloquent
时,您应该使用 $table 属性分配表名
例如:
In Laravel
when using Eloquent
you should assign a table name using the property $table
for example:
protected $table = 'some_thing';
否则它假定表名是模型名的复数形式,在这种情况下,对于 User
模型,表名应该是 users
.以下段落摘自 Laravel
网站:
Otherwise it assumes that the table name is the plural form of the model name and in this case for User
model the table name should be users
. Follwing paragraph is taken from Laravel
website:
表名
请注意,我们没有告诉 Eloquent 为我们的 Flight 使用哪个表模型.蛇案",类的复数名称将用作表名,除非明确指定了另一个名称.所以,在这个在这种情况下,Eloquent 将假设 Flight 模型将记录存储在航班表.
Note that we did not tell Eloquent which table to use for our Flight model. The "snake case", plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the Flight model stores records in the flights table.
// You may use this instead:
class Flight extends Model
{
// Explicit table name example
protected $table = 'my_flights';
}
因此,如果您在创建/命名 Laravel
期望的数据库表时不遵循此约定,那么您必须告诉 Laravel
表的名称模型中使用受保护的 $table
属性.
So, if you don't follw this convention when creating/naming your database tables that Laravel
expects then you have to tell Laravel
the name of the table for a model using a protected $table
property in your model.
这篇关于eloquent如何识别表格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!