按类别 ID laravel 检索 post

Retrieve post by category id laravel

我想检索给定类别的所有 post, 我正在开发 api,在输入时我将收到类别名称,然后我想通过它在 posts table 中的 id 检索该类别,我想这样做是因为如果某些更改将来的类别名称我不必在我的代码中更改它 我有这样的创造

PostController.php

  public function getPostsByCategory(Request $request)
{

    $posts=Posts::where('category',$request->category)->get();
    return response()->json(['posts'=>$posts]); 
}

Post 型号

<?php

 namespace App;

 use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{   

protected $fillable = [
    'post_title','post_description', 'category', 'user_id',
];

类别模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts_Category extends Model
{

}

你能帮我解决这个问题吗,请给我任何想法

您可以先通过名称获取类别,然后通过类别 id 过滤帖子

public function getPostsByCategory(Request $request)
{
    $category = Posts_Category::whereName($request->category)->firstOrFail();
    $posts=Posts::where('category',$category->id)->get();
    return response()->json(['posts'=>$posts]); 
}

我认为您正在寻找 with 预加载功能

您必须存储类别 ID 而不是类别名称..

class Posts extends Model
{   
     protected $fillable = [
        'post_title','post_description', 'category_id', 'user_id',
     ];

     public function category()
     {
          return $this->belongsTo(Posts_Category::class, 'category_id', 'id');
     }
}

用作

$posts = Posts::where('category_id',$request->category)->with('category')->get();

如果你真的想按名字搜索

$posts = Posts::whereHas('category', function ($q) {
   $q->where('category_name', 'like', "%{$request->category}%");
})->get();

您从一开始就以错误的方式执行此操作。最佳做法是将 category_id 存储在帖子 table 中,当然这仅适用于帖子和类别 table 之间需要 one-to-many 关系的情况。另外,除非您别无选择,否则我不建议您打破命名模型的惯例。我建议你更透彻地阅读本节

https://laravel.com/docs/5.6/eloquent-relationships

$posts = Posts::where('category_id', $category->id)->get();

我需要一个修复解决方案,我想从我的 laravel 博客项目

的特定类别中获取所有最新的 post

这些是我的模型

Category model

    public function posts()
    {
        return $this->belongsToMany('App\Post')->withTimestamps();
    }


Post model

 public function categories()
    {
        return $this->belongsToMany('App\Category')->withTimestamps();
    }

What's they next thing to do?
please help