[英]Laravel 5 where clause from another table
我有一個簡單的代碼,我想要做的是從另一個表訪問一個字段並將其放在我的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();
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');
}
}
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');
}
}
正如您在ReportController.php
看到的ReportController.php
,有一條評論說“應該是什么”,這是我想要修復的部分。 我想要做的是在我的雄辯查詢中訪問房間表中的type
字段。
我想要做的查詢是這樣的:
select * from `reservations` where `reservation_from` between '2015-10-29' and '2015-10-29' and `rooms.type` = "test"
有沒有辦法做到這一點? 謝謝。
您正在尋找的是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();
鏈接到文檔: 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();
我相信你是想做到這一點的。 根據您的問題更新更新。 with
方法采用字符串或數組。
$reservations = Reservation::with(['charge', 'client', 'room' =>
function($query){
$query->where('type', \Request::input('type'));
}])
->whereBetween('reservation_from', [$from, $to])
->orderBy('created_at')
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.