I have 3 models: Article
, Comment
, Reaction
.
Each article has many comments, and each comment has many reactions:
App\\Article:
class Article extends Model
{
public function comments() {
return $this->hasMany('App\Comment');
}
}
App\\Comment:
class Comment extends Model
{
public function article() {
return $this->belongsTo('App\Article');
}
public function reactions() {
return $this->hasMany('App\Reactions');
}
}
App\\Reaction:
class Reaction extends Model
{
public function comment() {
return $this->belongsTo('App\Comment');
}
}
In my ArticleController@index
I want to fetch comments and their reactions:
ArticleController:
public function index()
{
$articles = Article::with('comments')
->select('articles.*')
->leftjoin('comments', 'comments.article_id', '=', 'articles.id')
->get();
return view('wiki')->withArticles($articles);
}
I can loop through the comments ( $article->comments
), however I'm not sure how to do a with('reactions')
for the comments? ie,
@foreach($article->comments as $comment)
@foreach($comment->reactions)
// something like this...
@endforeach
@endforeach
you can do Nested Eager Loading
$article = Article::with('comments.reactions')
->leftjoin('comments', 'comments.article_id', '=', 'articles.id')
->select('articles.*')
->get();
You can also do this way
ArticleController:
public function index()
{
$articles = Article::with('comments')
->select('articles.*')
->get();
return view('wiki')->withArticles($articles);
}
App\\Article:
class Article extends Model
{
public function comments() {
return $this->hasMany('App\Comment')->with('reactions');
}
}
App\\Comment:
class Comment extends Model
{
public function article() {
return $this->belongsTo('App\Article');
}
public function reactions() {
return $this->hasMany('App\Reactions');
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.