【发布时间】:2019-01-12 05:06:12
【问题描述】:
我正在开发我的第一个 Laravel 项目,我想为 android 应用程序创建一个 REST Api。在我的系统中,我有两个表:categories 和 images。表images 有列category_id,这是一个外键,它引用category 表上的列id。
categories 表
//users table migration
class CreateCategoriessTable extends Migration
{
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
...
}
images 表
class CreateImagesTable extends Migration
{
public function up()
{
Schema::create('images', function(Blueprint $table){
$table->increments('id');
$table->string('name')
$table->integer('category_id')->unsigned();
$table->foreign('category_id')
->references('id')
->on('categories')
->onDelete('cascade');
$table->timestamps();
});
}
...
}
在Images 模型类中我做到了:
class Images extends Model
{
protected $fillable = ['name'];
protected $hidden = array('created_at', 'updated_at');
public function category(){
$this->belongsTo('App\Category');
}
}
我还创建了CategoryResource() 类:
class CategoryResource extends JsonResource
{
public function toArray($request)
{
return [
'id'=> $this->id,
'name' => $this->name,
];
}
}
所以,我用 API 方法创建了一个CategoryController,并配置了访问相应功能的路由。通过GET 的api/category/ url 重定向到我的控制器的index 函数,函数是这样的:
public function index()
{
$categories = Category::get();
return CategoryResource::collection($categories);
}
有了这个,我可以得到categories 表数据,但我想合并users 和images 表,并得到这样的响应:
[
{
'id': 1,
'name': 'category_name',
'image': 'image_name'
}
]
我该怎么做?
【问题讨论】: