dsqbh42082 2016-02-02 07:32
浏览 109
已采纳

附加子计数字段的Laravel查询

I have a table HouseholdProfile hasMany HouseholdMembers. I want to query all HouseholdProfile with an addional field of how many members of a the specific profile.

What I want:

     ID     Profile     No of Dependents
    1     Greg              3      <--- 3 is Number of child record in member table
    2     Roger             2

I have tried the query below but I think it lacks something

$query = HouseholdProfile::whereExists(function ($query) {
                $query->select(\DB::raw(count('household_members.id')))
                    ->from('household_members')
                    ->whereRaw('household_members.household_profile_id = household_profiles.id');
            })
        ->where('disaster_risk','like','%1%')->get();
  • 写回答

1条回答 默认 最新

  • dongtiao5094 2016-02-02 07:44
    关注

    If you don't explicitly need an extra column that contains the child count, then you could eager load the relations:

    $results = HouseholdProfile::with('household_members')
    ->where('disaster_risk','like','%1%')
    ->get();
    

    Then you can access the count for each record in your template like so:

    @foreach($results as $row)
        {{ $row->household_members->count() }}
    @endforeach
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重