我有3个模型:Article
,Comment
,Reaction
。
每篇文章都有很多评论,每条评论都有很多反应:
应用\文章:
class Article extends Model
{
public function comments() {
return $this->hasMany('App\Comment');
}
}
应用\评论:
class Comment extends Model
{
public function article() {
return $this->belongsTo('App\Article');
}
public function reactions() {
return $this->hasMany('App\Reactions');
}
}
应用\反应:
class Reaction extends Model
{
public function comment() {
return $this->belongsTo('App\Comment');
}
}
在我的ArticleController@index
我想提取评论及其反应:
ArticleController:
public function index()
{
$articles = Article::with('comments')
->select('articles.*')
->leftjoin('comments', 'comments.article_id', '=', 'articles.id')
->get();
return view('wiki')->withArticles($articles);
}
我可以循环浏览评论($article->comments
),但是我不确定如何为评论做with('reactions')
?即,
@foreach($article->comments as $comment)
@foreach($comment->reactions)
// something like this...
@endforeach
@endforeach
答案 0 :(得分:1)
你可以Nested Eager Loading
$article = Article::with('comments.reactions')
->leftjoin('comments', 'comments.article_id', '=', 'articles.id')
->select('articles.*')
->get();
答案 1 :(得分:0)
您也可以这样做
<强> ArticleController:强>
public function index()
{
$articles = Article::with('comments')
->select('articles.*')
->get();
return view('wiki')->withArticles($articles);
}
应用\文章:强>
class Article extends Model
{
public function comments() {
return $this->hasMany('App\Comment')->with('reactions');
}
}
应用\评论:强>
class Comment extends Model
{
public function article() {
return $this->belongsTo('App\Article');
}
public function reactions() {
return $this->hasMany('App\Reactions');
}
}