Laravel 6.2 :我在 index() 方法中从不同的数据中得到相同的 Id

Laravel 6.2 : I get the same Id from different data in index() method

我和 Laravel 一起工作,我需要从我的数据库中获得一些预订。

我使用查询生成器:

 public function getReservation($date)
    {
        $reservations = DB::table('reservations')
                        ->select('*')
                        ->join('agendas', 'reservations.agenda_id', '=', 'agendas.id')
                        ->whereDate('arrivee', $date)
                        ->get();

        return response($reservations);
    }

一切都很好,除了我对不同的资源有相同的 ID,我不知道为什么?

响应:

[
    {
        "id": 1,
        "created_at": "2020-02-07 12:30:28",
        "updated_at": "2020-02-07 12:30:28",
        "arrivee": "2020-02-12 13:00:00",
        "nbre_client": 4,
        "num_table": null,
        "remarque": null,
        "venu": 0,
        "formule": 0,
        "agenda_id": 1,
        "user_id": 1,
        "nom_client": "Stark",
        "prenom_client": null,
        "num_phone_client": "0658180058",
        "email_client": null,
        "confirmResa": null,
        "nameAg": "London"
    },
    {
        "id": 1,
        "created_at": "2020-02-07 12:30:28",
        "updated_at": "2020-02-07 12:30:28",
        "arrivee": "2020-02-12 13:30:00",
        "nbre_client": 2,
        "num_table": null,
        "remarque": null,
        "venu": 0,
        "formule": 0,
        "agenda_id": 1,
        "user_id": 1,
        "nom_client": "Banner",
        "prenom_client": null,
        "num_phone_client": "0658180058",
        "email_client": null,
        "confirmResa": null,
        "nameAg": "London"
    }
]

我数据库中的ID不一样(分别是2和3)

有人有什么想法吗?

解决方案

重复的 ID 很可能是您 agendas 的 ID,因为它们属于同一议程。

您可以将 select 更改为:

->select('reservations.*')

Eloquent 方式

您也可以通过 Eloquent 完成您所拥有的。

首先,您需要确保您的 Reservation 模型与您的 Agenda 模型具有 BelongsTo 关系。

public function agenda()
{
    return $this->belongsTo(Agenda::class);
}

那么你可以这样查询:

Reservation::whereHas('agenda', function ($query) use ($date) {
    $query->whereDate('arrivee', $date);
})->get();