0

我有一个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);
}
4

0 回答 0