如何使用Query Builder Laravel构建此RAW sql语句

时间:2018-05-22 12:19:25

标签: php mysql sql laravel

也许有人可以帮我用Laravel

中的Query Builder构建这个RAW SQL语句

**

DB:: select(DB:: raw("select min(heartrate) as hr, max(rotation) as rot, max(calories) as cal 
                                          from trainingsdatas, trainings 
                                          where trainings.user_id = $id 
                                          and trainingsdatas.training_id= trainings.id "));

**

这是一次尝试:

DB::table('trainingsdatas')
->join('trainings','trainings.id','=','trainingsdatas.training_id')
->min('heartrate as hr')
->max('rotation as rot')
->max('calories as cal')
->where('trainings.user_id','=', $id)
->get();

**

始终存在错误。语法似乎不正确。

2 个答案:

答案 0 :(得分:0)

尝试使用选择

DB::table('trainingsdatas')
->join('trainings','trainings.id','=','trainingsdatas.training_id')
->selectRaw('min(heartrate) as hr, max(rotation) as rot, max(calories) as cal')
->where('trainings.user_id','=', $id)
->get();

答案 1 :(得分:0)

试试这个

 $trainings = Trainings::query()->where('user_id', $id)
->join('trainingsdatas', 'trainings.id', '=', 'trainingsdatas.training_id')
->select(DB::raw('MAX(rotation) as rot'), DB::raw('MIN(heartrate) as hr'), DB::raw('MAX(calories) as cal'))