0

我正在开发一个 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."
}
4

1 回答 1

0

首先,您需要在 ItemsResouce 类中手动构造返回数组,如下所示:

public function toArray($request)
{
  return [
        "product_id" => $this->id,
        "product_name"=> $this->name,
        "sold" => $this->prod->sold,
        "total" => $this->prod->total
        ];
}

接下来你需要创建一个资源集合类,你可以命名它ItemCollection。您可以使用php artisan make:resource ItemCollection命令来创建类。该类应如下所示:

class ItemCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return parent::toArray($request);
    }
}

在控制器的 index 方法中,您可以像这样返回响应:

//use use App\Http\Resources\ItemCollection;
public function index()
{
    $items= Items::with('prod')->get();
    return new ItemCollection($items); //or use your send response helper method
}
于 2020-07-25T17:29:06.107 回答