我正在使用Laravel 5.3和模型Post
,我有一个追加属性:
/*
* toJson
*/
protected $appends = ['count'];
和魔法方法:
public function getCountAttribute()
{
return Offer::where('id', '=', $this->id)->count();
}
所以,当我得到一个Post
模型雄辩如Post::get()
,并获得返回json为例,我总是有这个属性count
在我的对象。
如何指定是否需要这个或另一个追加属性?
我检查了Eloquent模型是如何序列化的,不幸的是,要添加的字段列表在给定模型的所有实例之间不是共享的,我看到实现所需的唯一方法是遍历结果集并显式地启用所选属性的追加:
$posts = Post::all();
foreach ($posts as $post) {
// if you want to add new fields to the fields that are already appended
$post->append('count');
// OR if you want to overwrite the default list of appended fields
$post->setAppends(['count']);
}
您可以使用$post->getAttributes()
获得模型的属性,它在任何附加