【发布时间】:2019-02-11 04:31:04
【问题描述】:
我正在为网站开发 api,其中有博客和类别表
每个博客都属于类别 每个类别都有很多博客 好吗?
所以,我创建了一个 BlogController 并配置了访问相应功能的路由。
/api/blog/ url 通过 GET 重定向到我的控制器的 index 函数,函数如下所示:
public function index()
{
$blog = Blog::with('category')->get();
return response()->json($blog, 200);
}
返回这个(正确)
[
{
"id": 1,
"title": "title from blog",
"body": "texto do meu blog",
"category_id": 1,
"created_at": "2018-09-05 21:08:21",
"updated_at": "2018-09-05 21:08:21",
"category": {
"id": 1,
"name": "Web development",
"created_at": "2018-09-05 20:54:54",
"updated_at": "2018-09-05 20:54:54"
}
}
]
/api/blog/ url 通过 POST 被重定向到我的控制器的 store 函数,将数据存储在数据库中,函数如下所示:
public function store(Request $request)
{
$blog = new Blog($request->all());
$saved = $blog->save();
if ($saved) {
return response()->json($blog, 200);
}
return response()->json([
'message' => '400 Bad Request'
], 400);
}
然后返回(缺少类别信息)
{
"title": "title from blog",
"body": "texto do meu blog",
"category_id": "2",
"updated_at": "2018-09-06 00:56:13",
"created_at": "2018-09-06 00:56:13",
"id": 12
}
那么,缺少类别信息
在数据库中存储数据后,我需要它来响应该特定博客的类别信息
有人帮忙吗?
【问题讨论】:
-
图,
index函数返回分类信息的原因是Blog::with('category')。而store函数只返回对象。您可以使用$blog->loadMissing('category')加载关系,请参阅docs regarding Lazy Eager Load。 -
我明白了,谢谢 Bagus Tesa
标签: laravel rest api eloquent laravel-5.6