如何使用Eloquent - Laravel 5来加载和查询数据透视表

时间:2015-12-14 16:18:17

标签: php laravel laravel-5 eloquent

情况:单个约会可能与许多客户和许多用户有关,因此我在约会和客户之间有多对多的关系(数据透视表),而在约会和用户之间有另一个关系

我正在尝试编写雄辩的查询来获取客户的信息,包括所有相关的约会以及与这些约会相关的用户。

|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         |

Appointment.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();
}

在客户端/ ID显示页面上,我想显示客户端的信息,列出与此客户端相关的所有约会,并获取每个约会的相关用户信息。

不确定如何通过以下方式获取与约会相关的用户:

    $client = Client::with('appointment')
            ->where('id', '=', $id)
            ->firstOrFail();

1 个答案:

答案 0 :(得分:1)

这样就足够了:

$client = Client::with('appointment', 'appointment.user')->findOrFail($id);

这将加载具有给定ID的客户端,然后急切加载他们的约会,然后,对于每个约会,它将加载相关用户。