Laravel 5 where子句来自另一个表

wob*_*ano 3 php laravel eloquent laravel-5

我有一个简单的代码,我想要做的是从另一个表访问一个字段并将其放在我的where子句中.这是我的代码:

ReportController.php

$reservations = Reservation::with('charge', 'room', 'client')
-> whereBetween('reservation_from', [$from, $to])
-> where('room.type', \Request::input('type')) //what should this be
-> orderBy('created_at')
-> get();
Run Code Online (Sandbox Code Playgroud)

Room.php

class Room extends Model
{
    use SoftDeletes;
    protected $table = 'rooms';

    protected $fillable = ['id', 'roomNumber', 'type', 'price', 'description'];

    public function reservations() {
        return $this->hasMany('App\Reservation', 'id', 'room_number');
    }
}
Run Code Online (Sandbox Code Playgroud)

Reservation.php

class Reservation extends Model
{
    use SoftDeletes;
    protected $table = 'reservations';

    protected $fillable = ['roomNumber', 'clientId', 'reservation_from', 'reservation_to'];

    public function room() {
        return $this->belongsTo('App\Room');
    }

}
Run Code Online (Sandbox Code Playgroud)

架构: 在此输入图像描述

正如你在中看到的ReportController.php,有一条评论说"这应该是什么",这是我想要解决的部分.我想要做的是type在我的雄辩查询中访问房间表中的字段.

我想要做的查询是这样的:

select * from `reservations` where `reservation_from` between '2015-10-29' and '2015-10-29' and `rooms.type` = "test"
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?谢谢.

Tho*_*Kim 9

您正在寻找的是whereHas方法.

$reservations = Reservation::with('charge', 'room', 'client')
    ->whereBetween('reservation_from', [$from, $to])
    ->whereHas('room', function($query) {
        $query->where('type', '=', \Request::input('type'));
    })
    ->orderBy('created_at')
    ->get();
Run Code Online (Sandbox Code Playgroud)

链接到文档:http://laravel.com/docs/5.1/eloquent-relationships#querying-relations

编辑:

编辑此内容以澄清评论中的一些内容.

要创建方便,可重用的查询约束以使代码更清晰,可以使用查询约束:http://laravel.com/docs/5.1/eloquent#query-scopes

此外,因为查询可以链接,您可以执行以下操作:

// Create query with common constraints
$query = Reservation::with('charge', 'room', 'client')
    ->whereBetween('reservation_from', [$from, $to]);

// Ternary operator to decide whether or not to add whereHas constraint
$query = (\Request::input('type') == "all") ? $query : $query->whereHas('room', function($query) {
    $query->where('type', '=', \Request::input('type'));
});

// Finally, fetch the results sorted by 'latest', which is a convenient way of doing "orderBy('created')"
$reservations = $query->latest()->get();
Run Code Online (Sandbox Code Playgroud)