Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/257.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 拉威尔分组和_Php_Mysql_Laravel - Fatal编程技术网

Php 拉威尔分组和

Php 拉威尔分组和,php,mysql,laravel,Php,Mysql,Laravel,我试图用Laravel重现以下MySQL查询: SELECT SUM(distance) FROM trips WHERE user_id = 1 AND distance IS NOT NULL GROUP BY TRANSPORT $sortedDistances = Trip::where('user_id', 1) ->whereNotNull('distance') ->groupBy('transport') ->sum('distance

我试图用Laravel重现以下MySQL查询:

SELECT SUM(distance) FROM trips WHERE user_id = 1 AND distance IS NOT NULL GROUP BY TRANSPORT
$sortedDistances = Trip::where('user_id', 1)
    ->whereNotNull('distance')
    ->groupBy('transport')
    ->sum('distance');
当我在phpMyAdmin中执行它时,我得到以下结果:642778,0,1。以下是我对拉威尔的尝试:

SELECT SUM(distance) FROM trips WHERE user_id = 1 AND distance IS NOT NULL GROUP BY TRANSPORT
$sortedDistances = Trip::where('user_id', 1)
    ->whereNotNull('distance')
    ->groupBy('transport')
    ->sum('distance');

当我
var\u dump($sortedDistances)
时,我得到的只是
字符串(6)“642778”
。为什么这不是一个数组?

这应该可以得到一个数组

$sortedDistances = Trip::where('user_id', 1)
    ->whereNotNull('distance')
    ->select('transport', DB::raw('sum(distance) as TotalDistance'))
    ->groupBy('transport')
    ->get();

无需将whereNotNull('distance')提供为sum(null)=0是的,但通过跳过null行,它不是快了几分之一毫秒吗?;)谢谢,是的。我想我刚刚发现了使用ORM的一个局限性…