show last post from each category

前端 未结 3 1663
时光取名叫无心
时光取名叫无心 2020-12-11 10:30

I have two models Post and Category

// migration post

public function up()
{
    Schema::create(\'posts\', function (Blueprint $table) {
        $ta         


        
3条回答
  •  执笔经年
    2020-12-11 10:56

    Hiren was close, but you need to go from the category since your post is owned by the category

    $category->posts()->latest()->first();
    

    Alternatively you could work backwards:

    $post = Post::latest()->whereHas('category', function($q) use($category_id) {
        return $q->where('id', $category_id);
    })->first();
    

    For this to work you'll need to define your model relationships:

    Category Model needs this function:

    public function posts() 
    {
        return $this->hasMany(App\Post::class);
    }
    

    Post Model needs this function:

    public function category()
    {
        return $this->belongsTo(App\Category::class);
    }
    

    To respond to Alexey Mezenin, we can just pass a callback to with() to define which posts we want to pull in for each category, performing the correct eager load.

    Category::with(['posts' => function($q) {
        return $q->latest()->first();
    })->get(); 
    

提交回复
热议问题