Marco Roys Marco Roys - 2 months ago 14
MySQL Question

Laravel.get one related record

There is two models: Category and Post.

class Category extends Model
{

public function posts()
{
return $this->hasMany('App\Post','category_id');
}
}

class Post extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
}
}
//Get data
$data = Category::with(['posts' => function($query){
$query->orderBy('id','desc')->first();
}])->get();


In this case, all categories are displayed and only one post. I need to get from each category the one record post.


Example:

Category 1 - Post1

Category 2 - Post2

Category 3 - Post5

Category 4 - Post15

One category - one last post this category.

Answer

You have a Category with many Posts, but you just want to get the most recent post so you would add another relationship.

// Category.php
class Category extends Model
{
    // This gets ALL posts
    public function posts()
    {
        return $this->hasMany('App\Post','category_id');
    }

    // This gets the most recent post
    // I am ordering by created_at instead of ID, but you can use ID 
    // if it makes sense for your application)
    public function mostRecentPost()
    {
        return $this->hasOne('App\Post','category_id') // hasOne is the key here
                    ->orderBy('created_at', 'DESC');
    }
}

Then when you want to use it...

$data = Category::with('mostRecentPost')->get();