关于 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"
}
}
]
}
}
推荐文章: