2017-02-13 2 views
0

왼쪽 조인에 몇 가지 추가 필터를 추가하고 싶습니다. 그러나 어떻게 친절하게 도와 주는지 잘 모르겠습니다. 또한 Eloquent에서이 쿼리를 작성하는 방법을 알려줍니다. 내 쿼리는 아래와 같습니다 :Laravel 조인 5.3 단순하고 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); 
} 

예약 모델 Realtion

,
+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();