![](/img/trans.png)
[英]how to access values from result returned by eloquent model in laravel 5.1
[英]How to merge two eloquent model result attributes as new result in Laravel
我有一个 Laravel 产品 model 有一个称为细节的关系。 我想将这两个 eloquent 结果的属性合并在一起。
我的 $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" ]
$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" ]
我需要的是这个结果:
#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" ]
请注意,这些是 eloquent 结果,而不是简单的数组。
您可以使用API 资源class 或简单地使用map()
function 进行格式化,具体取决于您的项目/偏好。 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.