Php Laravel查询计数总计行数

Php Laravel查询计数总计行数,php,laravel,Php,Laravel,我有一个疑问: $counts = DB::table('projects') ->join('prject_links', 'prject_links.project_id', '=', 'projects.id') ->join('links', 'links.id', '=', 'prject_links.link_id') ->join('segments', 'segments.id', '=', 'links.segment_id')

我有一个疑问:

$counts = DB::table('projects')
    ->join('prject_links', 'prject_links.project_id', '=', 'projects.id')
    ->join('links', 'links.id', '=', 'prject_links.link_id')
    ->join('segments', 'segments.id', '=', 'links.segment_id')
    ->join('hthree_regions', 'hthree_regions.id', '=', 'segments.hthree_id')
    ->join('areas', 'areas.id', '=', 'hthree_regions.area_id')
    ->join('zone_regions', 'zone_regions.id', '=', 'areas.zone_id')
    ->select(
        'zone_regions.id as regions',
        'areas.id as provinces',
        'hthree_regions.id as cities',
        'segments.id as segments'
    )
    ->get();
我希望得到的结果是:

counts => [
  regions => 20,
  provinces => 10,
  cities => 7,
  segments => 5
];
我目前得到的是令人困惑的结果,如:


知道如何修复我的查询吗?

使用
groupBy
count(不同字段)
获取每个项目中字段的计数:

->选择raw(
“CONCAT('project',projects.id)作为项目,
将(不同区域_regions.id)计数为区域,
将(DISTINCT area.id)计算为省,
将(不同的hthree_regions.id)计数为城市,
将(不同的段.id)计数为段“
)
->groupBy('projects.id')
->get();

这可能是您的解决方案。运行它并让我知道这是否有帮助

$counts=DB::table('projects')
->join('prject\u links','prject\u links.project\u id','=','projects.id')
->join('links','links.id','=','prject\u links.link\u id')
->join('segments','segments.id','=','links.segments\u id'))
->join('hthree_regions','hthree_regions.id','=','segments.hthree_id'))
->join('areas','areas.id','=','hthree_regions.area_id'))
->join('zone_regions'、'zone_regions.id'、'='、'areas.zone_id')
->groupBy('projects.id')
->selectRaw(
'将(zone_regions.id)计数为区域',
'将(areas.id)计算为省',
'将(hthree_regions.id)计算为城市',
'将(segments.id)计数为段'
)
->get();

您是否尝试添加了一些
groupBy()
?@ChristopherHubert否我还没有这将是结果
->groupBy('projects.id')
它说传递给Lightning\Database\Query\Builder::selectRaw()的
参数2必须是数组类型,给定的字符串
谢谢错误消失了,请问如何将项目添加到此结果中?比如说
[项目:项目1,城市:5,…]
@Christophert Hubert why sum?我只需要计数我猜,假设我将得到
项目1有5个城市,项目2有17个城市
等等@mafortis我为每个项目添加了属性
项目id
是的,我现在正在尝试,我认为您应该使用
projects
而不是
project
它说传递给illumination\Database\Query\Builder::selectRaw()的
参数2必须是数组类型,给定的字符串
您可以将所有
selectRaw
参数放在一个数组中,只需用['count(zone\u regions.id)as regions',count(areas.id)作为省“,”计数(hthree_regions.id)作为城市“,”计数(segments.id)作为段“]在selectRaw中添加[]括号