我想要这个查询在laravel

时间:2019-06-13 09:41:16

标签: php laravel

我想知道如何使用联接在laravel中编写确切的查询,请帮助其他人解决此问题

select tickets.*  from `employees`  inner join `tickets` on  
 `employees`.`user_id` = `tickets`.`emp_id` inner join  `categories` on  
 `categories`.`acc_id` = `employees`.`acc_id` and `categories`.`id` = 
  (`tickets`.`cat_id` or `tickets`.`cat_id`=0)  where (`employees`.`user_id` = 11)

2 个答案:

答案 0 :(得分:2)

如果您使用的是普通查询构建器,

$result = DB::select(DB::raw("tickets.*"))
->join("tickets","employees.user_id","=","tickets.emp_id")
->join('categories', function ($join) {
            $join->on("categories.acc_id","=","employees.acc_id");
            $join->on("categories.id","=",DB::raw("(tickets.cat_id or tickets.cat_id=0)")

})->where("employees.user_id",11)->get();

答案 1 :(得分:1)

由于@Drakula Predator的回答很好

但我避免使用原始查询

$laravelWay = DB::table('employees')
                ->select('tickets.*')
                ->join('tickets','employees.user_id','=','tickets.emp_id')
                ->join('categories', function ($join) {
                        $join->on('categories.acc_id','=','employees.acc_id')
                            ->on('categories.id','=','tickets.cat_id')
                            ->orOn('tickets.cat_id','=','0');
                                })
                ->where('employees.user_id','=',11);