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

}

有更好的方法吗?因为我经常用这个,但它不合适.

推荐答案

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

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(),在你的视野中emits ->getComments()而不是->comments,你就可以出发了.

Laravel相关问答推荐

灯丝:设定模式标题

Nginx上带有SSL的Laravel混响

AJAX响应中未定义的全名

当使用Laravel eloquent查询100000条数据时速度很慢

使用 Laravel 计算页面浏览量

RuntimeException 未安装 Zip PHP 扩展

Laravel 5 将错误发送到Electron邮件

Laravel Eloquent - 随叫随到的加密/解密数据

laravel:如何在 Eloquent Query 中使用 LOWERCASE 函数?

用 laravel 表单确认删除?

向 Docker 上的 Artisan 推荐方式

Heroku CLI 安装错误:PATH 未更新,原始长度 1585 > 1024

如果值存在于另一个字段数组中,Laravel 验证规则

Laravel 4 - 如何将所有字段的所有验证错误消息作为 JSON struct 返回?

Laravel 迁移命名约定

如何重定向到laravel上的公共文件夹

无法捕获 Carbon 抛出的异常

Laravel 事件、监听器、作业(job)、队列之间的区别

Laravel 从公共删除目录

如何访问 Laravel 集合中的第 n 个项目?