1

我使用 laravel 8 并有 3 个表:产品、产品价格和产品发布者: 在此处输入图像描述

这是我的这种关系的产品模型:

    public function lastPrice(){
    return $this->hasMany(ProductPrice::class)->where('status','active')->orderBy('created_at','DESC')->distinct('publisher_id');
}

这是我的发布者关系的 productsPrice 模型:

    public function getPublisher(){
    return $this->belongsTo(ProductsPublisher::class,'publisher_id');
}

现在,我想为我的 api 使用 laravel 资源,我写了产品资源:

    public function toArray($request)
{
    return [
        'id' => $this->id,
        'price' => lastPrice::make($this->lastPrice),
        'status' => $this->status,
        'slug' => $this->slug,
        'title' => $this->title,
        'description' => $this->description,
        'txt' => $this->txt,
        'lang' => $this->lang,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ];

但是在 lastPrice 资源中,当我这样写时:

        return [
        'id' => $this->id,
        'main_price' => $this->main_price
    ];

它给了我这个错误:

此集合实例上不存在属性 [id]。

当我使用此代码时:

return parent::toArray($request);

得到响应,但因为我需要在我的 lastPirce 中为发布者使用另一个关系,所以我不能使用该代码,应该单独返回我的数据。我应该怎么做?谢谢

编辑 1: 这是我的控制器代码:

        $products = Product::where('id',$id)->where('slug',$slug)->where('status','confirm')->first();
    if(!$products){
        return $this->sendError('Post does not exist.');
    }else{
        return $this->sendResponse(new \App\Http\Resources\Products\Products($products), 'Posts fetched.');
    }

这是 sendResponse & sendError:

    public function sendResponse($result, $message)
{
    $response = [
        'success' => true,
        'data'    => $result,
        'message' => $message,
    ];

    return response()->json($response, 200);
}

public function sendError($error, $errorMessages = [], $code = 404)
{
    $response = [
        'success' => false,
        'message' => $error,
    ];

    if(!empty($errorMessages)){
        $response['data'] = $errorMessages;
    }

    return response()->json($response, $code);
}

谢谢。


编辑 2: 我将我的 lastPrice Resource toArray 函数更改为此并解决了我的问题,但我认为这不是一个干净的方法,有更好的主意吗?

    $old_data = parent::toArray($request);
    $co = 0;
    $new_data = [];
    foreach ($old_data as $index){
        $publisher_data =  Cache::remember('publisher'.$index['publisher_id'], env('CACHE_TIME_LONG') , function () use ($index)  {
            return ProductsPublisher::where('id' , $index['publisher_id'])->first();
        });
        $new_data[$co]['main_prices'] = $index['main_price'];
        $new_data[$co]['off_prices'] = $index['off_price'];
        $new_data[$co]['publisher'] = SinglePublisher::make($publisher_data);
        $new_data[$co]['created_at'] = $index['created_at'];

        $co++;
    }
    return $new_data;
4

0 回答 0