0
votes

Having a typical squeme with post & comments where a post have many comments and a comment belongs to one post:

Post Model:

 public function comments(){
    return $this->hasMany('App\Comment');
}

post migration:

Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');         
    });

Comment model:

 public function Post(){
    return $this->belongsTo('App/Post', 'id');
}

Comment migration:

   Schema::create('comments', function (Blueprint $table) {
        $table->increments('id');
        $table->date('date_comment');
        $table->unsignedInteger('post_id')->nullable()->default(null);
        $table->foreign('post_id')->references('id')->on('posts');
        });

I would like use eager loading in Laravel.

For example. How Can I obtain all posts with his most recent comment using eager loading?

I tried this:

$post = Post::with('comments:post_id, date_comment')->get();

But like this I obtain all comments. Any help please?

Best regards

EDIT:

foreach statement (Blade):

   @foreach($posts as $post)            
            <td>{{ $post->name }}</a></td>
            <td>
            {{ !empty($post->comments[0]) ? $post->comments[0]-> 
                date_comment : '' }}
            </td>                                      
   @endforeach
2

2 Answers

1
votes

You can constrain eager load

$posts = Post::with(['comments' => function($qry) {
    $qry->select('id','date_comment')->orderBy('date_comment', 'desc')->first();
}])->get();

Using this you can access all posts with their most recent comment.

If using the select method on query don't forget to add id field in the list.

To access date_comment of comments :

foreach($posts as $post) {
    var_dump(!empty($post->comments[0]) ? $post->comments[0]->date_comment : '');
}
2
votes

You need to make one more relation to retrieve the latest comment.

Post.php

public function comments(){
    return $this->hasMany('App\Comment');
}

public function latestComment(){
    return $this->hasOne('App\Comment')->orderBy('date_comment', 'desc');
}

Now You can retrieve it like this.

$posts = Post::with('latestComment')->get();

Note: Not tested.