我有一个模型beat.php
,它扩展了Eloquent并具有一个函数
public function posts()
{
return $this->belongsToMany('Post')->withPivot('deleted_at')->orderBy('created_at', 'desc');
}
在控制器中,我抓住了这样的节拍:
$beat = Beat::where('user_id', $data['owner']->id)->first();
在视图中,我循环播放这样的帖子:
@foreach ($beat->posts as $post)
...
@endforeach
问题是一些“Beats”有数百个帖子,导致PHP耗尽内存并且浏览器挂起。如何限制返回的结果数量?
我已经尝试过:
public function posts($limit)
{
return $this->belongsToMany('Post')->withPivot('deleted_at')->orderBy('created_at', 'desc')->take($limit);
}
像这样循环:
@foreach ($beat->posts(100) as $post)
...
@endforeach
但循环没有显示任何内容。有趣的是,它在模型中对$limit
进行硬编码并删除参数时起作用:
public function posts()
{
return $this->belongsToMany('Post')->withPivot('deleted_at')->orderBy('created_at', 'desc')->take(100);
}