我想在我的左连接中添加一些额外的过滤器,但我不知道如何善意帮助我。还告诉我如何在Eloquent中进行此查询。我的查询如下:
select * from `users`
join `halls` on `halls`.`user_id` = `users`.`id`
left join `bookings` on `bookings`.`hall_id` = `halls`.`id` AND month(`bookings`.`date`) = 2 and day(`bookings`.`date`) = 4 and year(`bookings`.`date`) = 2017
join `user_role` on `user_role`.`user_id` = `users`.`id`
join `roles` on `roles`.`id` = `user_role`.`role_id`
where
`roles`.`id` = 2 AND
(`bookings`.`id` is null OR `bookings`.`status` = 0 )
group by users.id
用户和角色有多对多关系,用户和大厅一对多和大厅和预订也有一对多的关系
用户模型关系
/**
* Many-to-Many relations with Role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles(){
return $this->belongsToMany(Role::class, 'user_role', 'user_id', 'role_id')->select('roles.name');
}
/**
* One-to-Many relations with halls.
*
* @return \Illuminate\Database\Eloquent\Relations\hasMany
*/
public function halls(){
return $this->hasMany(Hall::class);
}
霍尔模型关系
public function user(){
return $this->belongsTo(User::class, 'user_id', 'id');
}
public function bookings(){
return $this->hasMany(Booking::class);
}
预订模型实现
public function hall(){
return $this->belongsTo(Hall::class)->distinct();
}
答案 0 :(得分:0)
我不知道你为什么要使用group by而没有任何聚合函数。您的ORM如下所示
Users::join('halls', 'users.id', '=', 'halls.user_id')
leftJoin('bookings', function($join){
$join->on('halls.id', '=', 'bookings.hall_id');
$join->on(DB::raw('month(`bookings`.`date`) = 2 and day(`bookings`.`date`) = 4 and year(`bookings`.`date`) = 2017'));
})
->join('user_role', 'users.id', '=', 'user_role.user_id')
->join('roles', 'roles.id', '=', 'user_role.role_id')
->whereRaw('where
`roles`.`id` = 2 AND
(`bookings`.`id` is null OR `bookings`.`status` = 0 )')->get();