Mysql 以简单而雄辩的方式加入laravel 5.3
我想在我的左连接中添加一些额外的过滤器,但我不知道如何如此友好地帮助我。同时告诉我如何才能使这个查询有说服力。我的问题如下:Mysql 以简单而雄辩的方式加入laravel 5.3,mysql,database,join,eloquent,laravel-5.3,Mysql,Database,Join,Eloquent,Laravel 5.3,我想在我的左连接中添加一些额外的过滤器,但我不知道如何如此友好地帮助我。同时告诉我如何才能使这个查询有说服力。我的问题如下: 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`.`da
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();
}
我不知道为什么要使用没有任何聚合函数的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();
你能粘贴你定义的模型和关系吗?