我试图从数据库中返回一些最近的帖子,按日期排序,然后我想通过我的模型的getMonthAttribute()
访问器方法选择并返回帖子发布的月份。为了实现这一点,我使用了作用域查询。当我使用first()
只返回一个结果时,这一切都很好,但当我使用任何有效数字输入的take(1)
或take()
时,我会收到以下错误:
Undefined property: Illuminate'Database'Eloquent'Collection::$month
在我的模型中,我有这个月的属性访问器:
public function getMonthAttribute() {
return Carbon::createFromFormat('Y-m-d',$this->date)->format('F');
}
以及我的范围查询,以返回可变数量的最近帖子(我的代码中不起作用的部分):
public function scopeRecent($query, $take = 1) {
// Replace take with first and I no longer receive the above error.
return $query->where('status', '=', '1')->orderBy('date', 'DESC')->get()->take($take);
}
以下是我在视图中访问数据的方式:
{{ $post->recent()->month }}
有什么建议吗?
这是因为->first()
返回了一个雄辩的模型。使用get()
方法返回一个雄辩集合(雄辩模型的数组)。因此,您必须在集合上运行foreach,如下所示:
@foreach($post->recent() as $recent)
{{$recent->month }}
@endforeach