我想检索给定类别的所有帖子,
我正在开发api,在输入中我将收到类别名称,然后我想通过其在posts表中的id检索该类别,我想这样做,因为如果将来某些更改的类别名称我不必在我的更改码
我创造了这样的
PostController.PHP
public function getPostsByCategory(Request $request)
{
$posts=Posts::where('category',$request->category)->get();
return response()->json(['posts'=>$posts]);
}
发布模型
<?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
{
}
能帮到我吗,请建议我
解决方法:
public function getPostsByCategory(Request $request)
{
$category = Posts_Category::whereName($request->category)->firstOrFail();
$posts=Posts::where('category',$category->id)->get();
return response()->json(['posts'=>$posts]);
}