我正在使用Lumen编写一个REST API。我的例子有2个模型 User
和 Post
. Post
模型使用方法 belongsTo
以获得 User
模型,从而创建了这篇文章。我的目标是定义一个 配饰 这样我就可以得到帖子的作者的用户名,就像那样 Post::find($id)->author
. 所以根据文档,我这样做。
Post.php 。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
protected $appends = ['author'];
protected $fillable = [
'title',
'description'
];
protected $hidden = [
'user_id',
'created_at',
'updated_at'
];
public function user()
{
return $this->belongsTo('App\User', 'user_id');
}
public function getAuthorAttribute()
{
return $this->user->username;
}
}
现在getter很好用了,我可以很容易地得到指定的作者。Post
.
但如果我试图返回 Post
在JSON响应中,它也会给我返回一些奇怪的属性,如 user
似乎来自我 user()
方法,调用一个 belongsTo()
:
return response()->json(Post::find(2), 200);
{
"id": 2,
"title": "Amazing Post",
"description": "Nice post",
"author": "FooBar",
"user": {
"id": 4,
"username": "FooBar"
}
}
如果我使用 attributesToArray()
它的工作就像预期的那样。
return response()->json(Post::find(2)->attributesToArray(), 200);
{
"id": 2,
"title": "Amazing Post",
"description": "Nice post",
"author": "FooBar"
}
而且如果我把getter去掉 getAuthorAttribute()
和 $appends
声明,我没有得到意外的 user
属性。
但我不想每次都使用这个方法,而且如果我想返回所有的 Post
使用。
return response()->json(Post::all(), 200);
谁能告诉我,为什么我在使用... belongsTo
?
这种行为是由于性能。当你调用 $post->user
第一次,Laravel从数据库中读取了它,并把它放在了自己的位置上。寄存 $post->relation[]
以备下次使用. 这样下次Laravel就可以从数组中读取它, 并防止再次执行查询(如果你在多个地方使用它, 这将会很有用).
另外, 用户也是一个属性,Laravel将其合并为 $attributes
和 $relations
当你调用 $model->toJson()
或 $model->toArray()
Laravel的模型源码。
public function toArray() { return array_merge($this->attributesToArray(), $this->relationsToArray()); } public function jsonSerialize() { return $this->toArray(); }