php – 按类别id laravel检索帖子
作者:互联网
我想检索给定类别的所有帖子,
我正在开发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
{
}
能帮到我吗,请建议我
解决方法:
您可以先按名称获取类别,然后按类别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]);
}
标签:laravel-5-6,php,laravel,mysql,laravel-eloquent 来源: https://codeday.me/bug/20190828/1747946.html