我正在研究Laravel项目,我想为Android应用程序创建REST Api。在我的系统中,我有两个表:类别和图像。表格图像的列category_id是外键,它引用类别表上的列id。
类别表 //用户表迁移
class CreateCategoriessTable extends Migration
{
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
...
}
图像表
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();
});
}
...
}
我的图片模型:
class Images extends Model
{
protected $fillable = ['name'];
public function category(){
$this->belongsTo('App\Category');
}
}
我的类别模型:
class Categories extends Model
{
protected $fillable = ['name'];
public function images(){
$this->hasMany('App\Images');
}
}
因此,我使用API方法创建了一个CategoryController,并配置了访问相应功能的路由。通过GET的api / category / url重定向到我控制器的index函数,该函数是这样的:
public function index()
{
$categories = Category::get();
return CategoryResource::collection($categories);
}
这样,我可以获得类别表数据,但是我想合并用户表和图像表,并得到如下响应:
[
{
'id': 1,
'name': 'category_name',
'images': {'image_1','image_2','image_3',...}
}
]
我该怎么做?假设“类别”中有很多图片!
编辑:::
我创建的CategoryResource()类为:
class CategoryResource extends JsonResource
{
public function toArray($request)
{
return parent::toArray($request);
}
}
并将类别控制器更改为:
public function index()
{
$categories= Category::with('images')->get();
return CategoryResource::collection($categories);
}
假设返回:(实际上,在我的情况下,它返回以下json)
{
"data": [{
"id": 6,
"name": "Category1",
"created_at": "2018-07-31 16:18:51",
"updated_at": "2018-08-03 14:53:26",
"images": [{
"id": 23,
"category_id": 6,
"name": "category_6_31.jpg",
"created_at": "2018-07-31 16:18:51",
"updated_at": "2018-07-31 16:18:51"
}, {
"id": 27,
"category_id": 6,
"name": "category_6_752.jpg",
"created_at": "2018-08-02 01:35:52",
"updated_at": "2018-08-02 01:35:52"
}]
}, {
"id": 7,
"name": "Category2",
"created_at": "2018-07-31 16:19:50",
"updated_at": "2018-07-31 16:19:50",
"images": [{
"id": 24,
"category_id":7
"name": "product_7_1533053990.jpg",
"created_at": "2018-07-31 16:19:50",
"updated_at": "2018-07-31 16:19:50"
}]
}]
}
但是我想将JSON输出修改为:(删除不必要的列(键值对))为:
{
"data": [{
"id": 6,
"name": "Category1",
"images": [{
"id": 23,
"category_id": 6,
"name": "category_6_31.jpg",
}, {
"id": 27,
"category_id": 6,
"name": "category_6_752.jpg",
}]
}, {
"id": 7,
"name": "Category2",
"images": [{
"id": 24,
"category_id":7
"name": "product_7_1533053990.jpg",
}]
}]
}
如何编码CategoryResource类? 因为我做不到:::
return [
'id'=>$this->id,
'name'=>$this->name
]
这将引发错误。...
答案 0 :(得分:0)
尝试一下
public function index()
{
$categories = Category::with('images')->get();
return response()->json($categories,200);
}