php – 来自另一个表的Laravel 5 where子句
发布时间:2020-12-14 19:35:47 所属栏目:大数据 来源:网络整理
导读:我有一个简单的代码,我想要做的是从另一个表访问一个字段并将其放在我的where子句中.这是我的代码: ReportController.php $reservations = Reservation::with('charge','room','client')- whereBetween('reservation_from',[$from,$to])- where('room.type'
我有一个简单的代码,我想要做的是从另一个表访问一个字段并将其放在我的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('AppReservation','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('AppRoom'); } } 架构: 正如您在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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |