附加子计数字段的Laravel查询

时间:2016-02-02 07:32:51

标签: php laravel laravel-5

我有一张表 HouseholdProfile hasMany HouseholdMembers 。我想查询所有HouseholdProfile的附加字段,其中包含特定配置文件的成员数。

我想要的是什么:

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

我已尝试过以下查询,但我认为它缺少一些东西

$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 个答案:

答案 0 :(得分:1)

如果您没有明确需要包含子计数的额外列,那么您可以急切加载关系:

hive>create table testTableNew(id int ,name string ) clustered by (id) into 2 buckets stored as orc TBLPROPERTIES('transactional'='true');

然后您可以访问模板中每条记录的计数,如下所示:

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