2017-02-13 66 views
0

我想在我的左连接中添加一些额外的过滤器,但我不知道如何如此善意地帮助我。并且还告诉我如何在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`.`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没有任何聚合函数。您的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();