【发布时间】:2018-09-05 23:03:57
【问题描述】:
我正在开发一个 Laravel 项目,我想为网站创建一个 REST API。在我的系统上,我有两个表:
博客和类别。表 blogs 有 category_id 列,这是一个引用 category 表中列 ID 的键。
博客迁移
class CreateBlogsTable extends Migration
{
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->longtext('body');
$table->string('category_id');
$table->timestamps();
});
}
.....
}
类别迁移
class CreateCategoriesTable extends Migration
{
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
....
}
我的博客模型
class Blog extends Model
{
protected $fillable = ['title', 'body', 'category_id'];
public function category() {
return $this->hasMany('app\Category');
}
}
我的博客模型
class Category extends Model
{
protected $fillable = ['name'];
public function blog() {
return $this->hasMany('app\Blog');
}
}
所以,我创建了一个 BlogController 并配置了访问相应 API 函数的路由。
api/blogs/via GET是给我的控制器的index函数,函数长这样:
public function index()
{
$blog = Blog::all();
return response()->json($blog, 200);
}
有了这个,我可以从 blogs 表中获取数据
[
{
"id": 1,
"title": "title from my blog",
"text": "text body here",
"category_id": "2",
"created_at": "2018-09-05 21:08:21",
"updated_at": "2018-09-05 21:08:21"
}
]
但我想合并博客和类别表,并得到类似的回应
[
{
"id": 1,
"title": "title from my blog",
"text": "text body here",
"category_id": "2",
"created_at": "2018-09-05 21:08:21",
"updated_at": "2018-09-05 21:08:21"
"category": [{
"id": 2,
"name": "Development"
}]
}
]
有人帮忙吗?
【问题讨论】:
-
category必须是BelongsTo关系。
标签: laravel rest api laravel-5 laravel-5.6