Laravel 关系和数据透视表

Laravel relationships and pivot tables

我正在开发我的第一个 laravel 应用程序,现在我正处于为我的内容类型创建一些关系的阶段。

在应用程序中,我可以创建一个约会,在这样做的过程中还会保存详细信息并创建一个新客户。但是我希望我的用户能够看到他们的客户 "history" 并看到他们已经预订的所有约会。

到目前为止,我已将 hasMany 关系添加到我的客户端模型中,并在约会模型中添加了相反的 hasOne。因此,到目前为止我的想法是一个客户可以有很多约会,但一个约会只能有一个客户。

然而...

我真的很难将两者连接在一起,理想情况下我需要做这样的事情:-

对于 X 客户 ID,获取与客户 ID 匹配的所有约会

在这种情况下,您会在哪里使用枢轴 table 来管理它?如果是这样,您将处理模型中 ID 的 attaching/deattaching 的逻辑放在哪里?

或者我的电话中是否缺少某些内容,因为我的客户端模型中的约会功能只有以下内容:-

       return $this->hasMany('App\Appointment');

我还需要传递其他信息吗?

我已经阅读了文档,但我完全一无所知并且来自 WP 背景,所以任何帮助都会很棒!

既然你在谈论 a one-to-many relationship,你就不需要支点 table。相反,您的 appointments table 应该有一个链接到客户端的 client_id 列。

要获取客户的所有约会,您只需获取 appointments 属性(假设您的关系方法也称为 appointments():

$appointments = $client->appointments;

// OR

$appointments = \App\Client::find($client_id)->appointments;

由于 class 上不存在 属性,Laravel 将查找具有相同名称的关系方法。一旦找到它 Laravel 将查询约会 table 以查找具有该客户 ID 的条目和 return 他们 in a Collection.

关系方法在存储新约会时也有帮助:

$client->appointments()->create(['date' => request('date'), ...]);

这里您不需要手动将 client_id 添加到约会中,因为 Laravel 知道这种关系。

您在 methods/table 列的命名等方面有一些灵活性,但我通常发现最好坚持使用 the Laravel conventions

您可以在此处为当前上下文使用一对多关系。

<?php
// Appointment model
class Appointment extends Model
{
    ...
    /**
     * Get the client associated with the Appointment.
     */
    public function client()
    {
        return $this->hasOne('App\Client', 'client_id');
    }
    ...
}

// client model
class Client extends Model
{
    ...
    /**
     * Get the Appointments associated with the client.
     */
    public function appointments()
    {
        return $this->hasMany('App\Appointment');
    }
    ...
}

// query to fetch client's appointments
Client::find(1)->with(['appointments']);

试试这个方法

//In your Appointment Model
class Appointment extends Model
{
    public function client()
    {
        return $this->belongsTo('App\Client'); 
    }
}

//In your Client Model
class Client extends Model
{
    public function appointments()
    {
        return $this->hasMany('App\Appointment'); //if the foreign column in your appointments table is named different the client_id, the specify that column ('App\Appointment', 'id_of_client)
    }
    ...
}

// query to fetch client's appointments
$client = Client::findOrFail(1)->with(['appointments']);