Mus*_*kat 7 php rest laravel laravel-5
我要做的是将每篇文章的评论附加到文章对象,但问题是我每次都需要请求不同数量的评论.
由于某种原因,我需要使用mutators,因为有时我要求50篇文章,我不想循环结果并附加注释.
那么是否可以执行以下操作以及如何传递额外参数.
这个型号:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是控制器:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我不想做的是:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?因为我经常使用它而且接缝不对.
Den*_*nko 10
从Laravel源代码判断,不 - 不可能将额外的参数传递给这个魔术存取方法.
最简单的解决方案就是在你的类中添加另一个额外的方法,它接受你想要的任何参数 - 你可以使用该方法而不是magic属性.
例如.只需将您重命名getCommentsAttribute()
为getComments()
火,->getComments()
而不是->comments
在您的视图中,您就可以去了.
归档时间: |
|
查看次数: |
5900 次 |
最近记录: |