首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将两个有说服力的模型结果属性合并为Laravel中的新结果

如何将两个有说服力的模型结果属性合并为Laravel中的新结果
EN

Stack Overflow用户
提问于 2022-01-27 11:30:24
回答 1查看 409关注 0票数 1

我有一个Laravel产品模型,它有一个叫做细节的关系。我想把这两个雄辩的结果的特点结合在一起。

我的$product属性如下:

代码语言:javascript
运行
复制
#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"
  ]

此外,$product->details属性如下所示:

代码语言:javascript
运行
复制
#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"
  ]

我需要的是这个结果:

代码语言:javascript
运行
复制
#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"
  ]

请注意,这些都是雄辩的结果,并不是一个简单的数组。

EN

回答 1

Stack Overflow用户

发布于 2022-01-27 14:03:02

您可以使用API资源类进行格式化,也可以根据项目/首选项使用map()函数。API资源可能如下所示:

代码语言:javascript
运行
复制
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,
            ...
        ];
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70877825

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档