需求,查询文章列表,以及文章列表下的评论。可是每篇文章评论只须要查询出2条便可(一篇文章可能有几百个评论)。laravel
//---------------------Article模型的关联表配置以下---------------------------------- public function comments(){ return $this->hasMany('Modules\Type\Entities\comments', 'article_id', 'id') ->select(['id','name'])->limit(2); //这里就限制了只查询2条评论,同时select()也限制只查询comments的id 和name }
$articles=Article::all(); //查询出对应条件的文章 $articles->each(function ($articles) { $articles->load('comments'); }); //对每一个文章进行加载对应的评论关联关系 return $articles;
参考了Laravel官方Github贡献者,themsaid讨论给出的答案issuehttps://github.com/laravel/framework/issues/18014git