情况:一个约会可以与许多客户端和许多用户相关,因此我在约会和客户端之间有一个多对多关系(透视表),在约会和用户之间有另一个关系
我正试图编写一个雄辩的查询来获取客户的信息,包括所有相关的约会以及与每个约会相关的用户。
表格
|appointment|
| |
-------------
| id |
| time |
| created_at|
| updated_at|
| client | | appointment_client |
| | | (pivot table) |
------------- ----------------------
| id | | appointment_id |
| name | | client_id |
| created_at| | created_at |
| updated_at| | updated_at |
| user | | appointment_user |
| | | (pivot table) |
------------- ----------------------
| id | | appointment_id |
| name | | user_id |
| created_at| | created_at |
| updated_at| | updated_at |
预约.php型号
public function client()
{
return $this->belongsToMany('App'Client')->withTimestamps();
}
public function user()
{
return $this->belongsToMany('App'User')->withTimestamps();
}
Client.php型号
public function appointment()
{
return $this->belongsToMany('App'Appointment')->withTimestamps();
}
User.php型号
public function appointment()
{
return $this->belongsToMany('App'Appointment')->withTimestamps();
}
在client/id show页面上,我想显示客户的信息,列出与该客户相关的所有约会,并获取每个约会的相关用户信息。
不确定如何获得与约会相关的用户:
$client = Client::with('appointment')
->where('id', '=', $id)
->firstOrFail();
只做就足够了
$client = Client::with('appointment', 'appointment.user')->findOrFail($id);
这将加载具有给定ID的客户端,然后急切地加载他们的约会,然后,对于每个约会,它将加载相关用户。