在Laravel中如何将额外的数据传递给mutators和accessors [英] In laravel how to pass extra data to mutators and accessors

查看:41
本文介绍了在Laravel中如何将额外的数据传递给mutators和accessors的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是将每篇文章的评论附加到articles对象,但是问题是我每次都需要请求不同数量的评论.

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篇文章,并且我不想遍历结果并添加评论.

and for some reason I need to use mutators for that, because some times I request 50 articles and I don't want to loop through the result and append the comments.

因此可以执行以下操作以及如何传递额外的参数.

So is it possible to do something like the following and how to pass the extra argument.

此模型:

    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);

        }
    }

这是控制者:

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;
    }    

}

我不想做的是:

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);
    }    

}

有更好的方法吗?因为我经常使用它,而且接缝不正确.

Is there a better way to do it? because I use this a lot and it does not seams right.

推荐答案

从Laravel源代码判断,不-不可能将额外的参数传递给该魔术访问器方法.

Judging from the Laravel source code, no – it's not possible to pass an extra argument to this magic accessor method.

最简单的解决方案是在类中添加另一个额外的方法,该方法确实接受您希望的任何参数-您可以使用该方法代替magic属性.

The easiest solution is just to add another, extra method in your class that does accept any parameters you wish – and you can use that method instead of magic property.

例如.只需将您的 getCommentsAttribute()重命名为 getComments()并触发-> getComments()而不是->评论在您看来,您很高兴.

Eg. simply rename your getCommentsAttribute() to getComments() and fire ->getComments() instead of ->comments in your view, and you are good to go.

这篇关于在Laravel中如何将额外的数据传递给mutators和accessors的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆