我正在开发一个 Laravel 项目,我想为网站创建一个 REST API。在我的系统上,我有两个表:我的表是 Item 和 Product 表,它们都具有一对一的关系我想要来自两个表的 json 响应,如下所示
"data": [
{
"product_id": 3,
"product_name": "xyz",
"sold": 0,
"total": 500
}
}
]
但我得到的实际格式如下
"data": [
{
"product_id": 3,
"product_name": "xyz",
"prod": {
"id": 1,
"products_id": 3,
"sold": 0,
"total": 500
}
}
]
我的项目控制器类
class ItemCont extends BaseController
{
public function index()
{
$items= Items::all();
return $this->sendResponse(ItemResource::collection($items), 'Items retrieved successfully.');
}
}
我的 ItemResource 类
class ItemResource extends JsonResource
{
public function toArray($request)
{
return parent::toArray($request);
}
}
物品型号
class Items extends Model
{
public $timestamps = false;
protected $primaryKey = 'product_id';
protected $guarded = [];
protected $fillable = [
'product_name'
];
public function prod(){
return $this->hasOne('App\Products','products_id','product_id');
}
}
products Model
class Products extends Model
{
public $timestamps = false;
protected $primaryKey = 'id';
protected $guarded = [];
protected $fillable = [
'sold','total'
];
public function item(){
return $this->belongsTo('App\Items','product_id','products_id');
}
}
products resource class
class ProductResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
谢谢我尝试过的第二种方法是我的 ItemResource 类
class ItemResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
//return parent::toArray($request);
return [
'Product_id' => $this->id,
'product_name' => $this->name
//'products' => new Products($this->products),
//'sold' => $this->sales,
//'total' => $this->total,
];
}
我的产品资源类
class ProductResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
"sold" => $this->sales,
"total"=>$this->total
];
// return parent::toArray($request);
}
和我的 ItemController 类
class ItemCont extends BaseController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$items= Items::with('prod')->get();
return $this->sendResponse(ItemResource::collection($items), 'Items retrieved successfully.');
}
第二种方法尝试的响应是
{
"success": true,
"data": [
{
"Product_id": null,
"product_name": null
},
{
"Product_id": null,
"product_name": null
}
],
"message": "Items retrieved successfully."
}