What I'm trying to do is to append the comments of each article to the articles object, but the problem is that I need to request different number of comments each time.
出于某种原因,我需要使用mutators,因为有时我请求50篇文章,而我不想遍历结果并附加 comments .
那么,是否有可能执行以下操作,以及如何传递额外的参数.
This the Model:个
class Article extends Model
{
protected $appends = ['user', 'comments', 'media'];
public function getCommentsAttribute($data, $maxNumberOfComments = 0)
{
// I need to set maxNumberOfComments
return $this->comments()->paginate($maxNumberOfComments);
}
}
Here is the controller:
class PostsController extends Controller
{
public function index()
{
//This will automatically append the comments to each article but I
//have no control over the number of comments
$posts = Post::user()->paginate(10);
return $posts;
}
}
What I don't want to do is:个
class PostsController extends Controller
{
public function index()
{
$articles = Post::user()->all();
$number = 5;
User::find(1)->articles()->map(function(Article $article) {
$article['comments'] = $article->getCommnets($number);
return $article;
});
return Response::json($articles);
}
}
有更好的方法吗?因为我经常用这个,但它不合适.