使用 eloquent 模型映射加入查询

Join query using eloquent model mapping

我正在尝试这样做

select notifications.id, reservations.number from 
notifications 
JOIN reservations 
ON notifications.reservation_id = reservations.id 
WHERE notifications.status = 1

使用 eloquent 所以我有这个

$await = Notification::with('Reservation')->
select('notifications.id', 'reservations.number')
->where('notifications.status', '=', 1)->get();

return Response::json($awaitLists);

在我的通知模型中

public function Reservation() {
        return $this->belongsTO('Reservation');
    }

在我的预订模型中

public function notification() {
        return $this->hasMany('Notification');
    }   

所以notification属于reservation,而reservation是一对多的关系

我的问题是为什么我尝试过的方法不起作用。我不断收到未知列 'reservation.number',但我在预订 table 中确实有名为数字的列。我知道他们是一种使用 eloquent 关系映射器来做到这一点的方法。

您看到的错误是因为预加载关系实际上并不执行连接。它使用两个单独的查询,然后在查询后分配关系字段 运行.

因此,当您执行 Notification::with('Reservation')->get() 时,它是 运行 两个 SQL 语句,大约:

Notification::with('Reservation')->get();
// select * from notifications;
// select * from reservations where id in (?, ?, ...);

如果您有兴趣,可以通过 dd(DB::getQueryLog()) 查看实际查询 运行。

你如何前进取决于你需要做什么。如果您需要完全复制现有查询,则需要手动执行连接。

$notifications = Notification::select('notifications.id', 'reservations.number')
    ->join('reservations', 'notifications.reservation_id', '=', 'reservations.id`)
    ->where('notifications.status', '=', 1)
    ->get();

foreach($notifications as $notification) {
    print_r($notification->number);
}

否则,您可以直接使用 Laravel 构建的对象:

$notifications = Notification::with('Reservation')->where('status', '=', 1)->get();

foreach($notifications as $notification) {
    print_r($notification->Reservation->number);
}

应该这样做:

$notifications = Notification::where('status','=',1)->get();

foreach($notifications as $notification) {
    $id = $notification->id;
    $num = $notification->reservation->number;

    $await = [$id,$num];
    var_dump($await);
}