关于 ORM 模型的 belongsToMany 如何在已查询到的数据里添加自定义的数据

问题的缘由以及问题的出现

如图所示:

我现在存在着三张表

数据表关系

分别为:events (事件表),employees (员工表) 与 event_employees (事件员工表)。其中 event_employees 表充当为 事件表与员工表的中间表。

这时我准备获取以这种模式为基准,去获取如下格式的数据。

{
    "data" : {
        "id" : 1,
        "name" : "event name",
        "code" : "event code",
        "type" : "course",
        "photo" : "image_url",
        "address" : "event address",
        "date" : "2020-12-11",
        "permission" : "public",
        "status" : "pending",
        "employees" : [
            {
                "id" : 1,
                "email" : "employee@qq.com",
                "photo" : 'image_url',
                "scopre" : "course",
                "firstname" : "firstname",
                "lastname" : "lastname",
                "response" : "pending"
            }
        ]
    }
}

其中events , event_employees , employees 三个模型如下。

事件表

<?php
namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class Event extends Model
{
    public $timestamps = false;

    protected $guarded = [];

    protected $hidden = [
        'client_id','photo'
    ];

    public function client()
    {
        return $this->belongsTo(Client::class);
    }

    public function eventEmployees()
    {
        return $this->hasMany(EventEmployee::class);
    }

    public function employees()
    {
        return $this->belongsToMany(Employee::class,"event_employees")->withPivot('response');
    }
}

员工表

<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    protected $hidden = [
        "is_admin","password","login_token"
    ];

    public function eventEmployee()
    {
        return $this->belongsTo(EventEmployee::class,"employee_id","id");
    }
}

事件员工表

<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;

class EventEmployee extends Model
{
    protected $guarded = [];

    public $timestamps = false;

    public function employees()
    {
        return $this->hasMany(Employee::class,"id","employee_id");
    }

    public function event()
    {
        return $this->belongsTo(Event::class);
    }
}

在把数据模型里的方法定义好后,我开始执行我的代码;

第一次采用的是 hasMany 方法,代码以及查到的数据如下:
(很明显,与我预期的数据格式相差巨大)

// code
return ['data' => Event->with("eventEmployees.employees")->find($id)];

// data
{
    "data": {
        "id": 300,
        "code": "suscipit",
        "name": "Scotty Kuhic",
        "address": "West",
        "date": "2020-03-28",
        "type": "training",
        "permission": "private",
        "status": "accepted",
        "event_employees": [
            {
                "id": 28,
                "employee_id": 1,
                "event_id": 300,
                "response": "pending",
                "employees": [
                    {
                        "id": 1,
                        "email": "admin@zacmp.com",
                        "first_name": "admin",
                        "last_name": "admin",
                        "photo": null,
                        "scope": "course"
                    }
                ]
            }
        ]
    }
}

第二次采用的是 belongsToMany 方法,代码以及查到的数据如下:
(这一次能很明显的看到我获取到数据和我想要获取到的数据格式已经十分接近了,就差直接把response直接塞入到employees的子对象里了)

// code
return ['data' => Event->with("employees")->find($id)];

// data
{
    "data": {
        "id": 300,
        "code": "suscipit",
        "name": "Scotty Kuhic",
        "address": "West",
        "date": "2020-03-28",
        "type": "training",
        "permission": "private",
        "status": "accepted",
        "employees": [
            {
                "id": 1,
                "email": "admin@zacmp.com",
                "first_name": "admin",
                "last_name": "admin",
                "photo": null,
                "scope": "course",
                "pivot": {
                    "event_id": 300,
                    "employee_id": 1,
                    "response": "pending"
                }
            }
        ]
    }
}

我该如何解决这个问题?即将response 往上一级的数据里插入?望解答!

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 3

呃,你是指这样写吗?

file

这样写确实可以获取到这种格式的数据,不过相对来讲与我写的循环嵌套来讲,代码量数多,sql查询少。

嘛,也算是十分感谢了! :smiley:

4年前 评论

@Rarin_2002

// Controller
$event = Event::query()->with("employees")->find($id);
return EventResource::make($event);

// EventResource
public function toArray($request)
{
    return [
        .
        .
        .
        'employees' => EmployeeResource::collection($this->whenLoaded('employees'))
    ];
}

// EmployeeResource
public function toArray($request)
{
    return [
        .
        .
        .
        'response' => $this->pivot->response
    ];
}

这样,结构清晰一点

4年前 评论
Rarin_2002 (楼主) 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!