【问题标题】:Joins in laravel 5.3 in simple and Eloquent以简单和雄辩的方式加入 laravel 5.3
【发布时间】:2017-07-01 12:49:51
【问题描述】:

我想在左连接中添加一些额外的过滤器,但我不知道如何帮助我。还告诉我如何在 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

user 和 role 有多对多的关系,user 和 hall 一对多,hall 和 bookings 也有一对多的关系 用户模型关系

/**
     * 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();
}

【问题讨论】:

  • 你能粘贴你定义的模型和关系吗?

标签: mysql database join eloquent laravel-5.3


【解决方案1】:

我不知道你为什么要在没有任何聚合函数的情况下使用 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();

【讨论】:

    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2017-04-28
    • 2018-10-11
    • 2018-09-27
    • 2017-08-03
    相关资源
    最近更新 更多