Я работаю над проектом 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."
}