我有一个简单的代码,我想要做的是从另一个表访问一个字段并将其放在我的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中看到的那样,有一条评论说“应该是什么”,这是我想要修复的部分.我想要做的是在我的雄辩查询中访问房间表中的类型字段.
我想要做的查询是这样的:
select * from `reservations` where `reservation_from` between '2015-10-29' and '2015-10-29' and `rooms.type` = "test"
有没有办法做到这一点?谢谢.
解决方法
您正在寻找的是whereHas方法.
$reservations = Reservation::with('charge','client') ->whereBetween('reservation_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',$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();