Eloquent 的模型中不需要列名(字段).正如您所指出的,只需要定义确定模型与其他模型之间关系的函数.
It isn't necessary to include them, because of the reason you mentioned (Laravel does a select *
and then adds all of the returned rows to the model object as public properties). This is a process dubbed hydration and you can see exactly what is happening by digging into the Laravel source. Here's a summary of what happens:
- 你打电话(例如)
Users::find(123);
Illuminate\Database\Eloquent\Model::find()
个电话Illuminate\Database\Eloquent\Builder::find()
find()
构造SELECT * FROM users WHERE id = 123
查询,然后通过调用Illuminate\Database\Eloquent\Builder::first()
返回第一个结果
first()
通过呼叫Illuminate\Database\Query\Builder::take()
增加LIMIT 1
- Then
first()
sets the columns to be retrieved (*
by default) by calling Illuminate\Database\Eloquent\Builder::get()
.
get()
returns an Illuminate\Database\Eloquent\Collection
by using the return value of Illuminate\Database\Eloquent\Builder::getModels()
getModels()
实际执行查询,然后为返回的每一行调用Illuminate\Database\Eloquent\Model::newFromBuilder()
newFromBuilder()
creates a new instance of the model and sets the columns (fields) by calling Illuminate\Database\Eloquent\Model::setRawAttributes()
为了简化过程,我省略了一些不相关的事情,比如急于加载,但基本上每个查询都是这样.
You make a good point that knowing the fields beforehand can be helpful for autocompletion. Because of the nature of setRawAttributes()
it is perfectly OK to declare all column names (fields) in your model (just make sure they are public). The convention, though (and for you sanity), is to omit them. Such declarations should be left to migration files.
After further examination of the source, it is not ok to declare the fields beforehand. This is because the actual attribute values are stored in an $attributes
property and then accessed by the magic method __get()
. The trouble here is that by defining the properties beforehand, you will prevent __get()
from being called when you access the fields. Therefore, this is not an option.
However, there are ways to hint to editors (like PhpStorm) about the existence of properties without explicitly defining them.