laravel5.7 模型关联 (select 指定查询字段、where关联条件、sum 关联求和)

//指定查询字段

   ->with(['certifications'=>function($a){   //certifications是关联的模型名
                $a->where('status',1)->select('user_id','status');        //user_id   是两个表的关联键,即使不查询user_id 也要把user_id 查询出来
            }])
         
//where关联条件
   ->when($by_income, function ($query) use ($by_income) {                                     //when 方法
                 $query->whereHas('incomeuser', function ($query) use ($by_income) {      //whereHas       //incomeuser是关联的模型名
                     $query->where('by_income',$by_income);
                });
            })
//sum 关联求和
 ->with(['incomedetails'=>function($d){
                $d->groupBy('user_id')->whereIn('income_type',['recharge','viprecharge','srecharge'])
                ->selectraw('user_id ,sum(income) as recharge_income');
            }])

你可能感兴趣的:(Laravel)