简体   繁体   English

如何将两个 eloquent model 结果属性合并为 Laravel 中的新结果

[英]How to merge two eloquent model result attributes as new result in Laravel

I have a Laravel product model that has a relation called details.我有一个 Laravel 产品 model 有一个称为细节的关系。 I want to merge the attributes of these two eloquent results together.我想将这两个 eloquent 结果的属性合并在一起。

My $product attributes are like this:我的 $product 属性是这样的:

 #attributes: array:7 [▼ "id" => 1 "title" => "test" "slug" => "test" "html" => null "published_at" => "2022-01-27 11:01:00" "created_at" => "2022-01-27 11:04:15" "updated_at" => "2022-01-27 11:05:30" ]

Also $product->details attributes are like this: $product->details 属性也是这样的:

 #attributes: array:6 [▼ "id" => 1 "model" => "test" "sku" => "test" "base_price" => null "created_at" => "2022-01-27 11:04:15" "updated_at" => "2022-01-27 11:05:30" ]

What I need is this result:我需要的是这个结果:

 #attributes: array:10 [▼ "id" => 1 "title" => "test" "slug" => "test" "html" => null "model" => "test" "sku" => "test" "base_price" => null "published_at" => "2022-01-27 11:01:00" "created_at" => "2022-01-27 11:04:15" "updated_at" => "2022-01-27 11:05:30" ]

Notice that these are the eloquent results and are not a simple array.请注意,这些是 eloquent 结果,而不是简单的数组。

You could do the formatting using a API Resource class or simply by using a map() function depending on your project/preference.您可以使用API 资源class 或简单地使用map() function 进行格式化,具体取决于您的项目/偏好。 The API Resource may look something like this: API 资源可能如下所示:

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'html' => $this->html,
            "model" => $this->details?->model,
            "sku" => $this->details?->sku,
            "base_price" => $this->details?->base_price,
            ...
        ];
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM