简体   繁体   中英

Laravel get all groups along with the count of each groups group members using join query

I have two tables 'Group'('id', 'title', 'description') and 'Group_members'('id', 'group_id', 'user_id'). When ever a user joins a group, a row is created in 'group_members' table.

What I need is to fetch all groups along with the number of members in each group, something like:-

[
    {
        id: 1
        title: group1
        description: lorem ipsum
        member_count: 5
    }{
        id: 2
        title: group2
        description: lorem ipsum
        member_count: 7
    }
]

What I have done so far is,

    DB::table('group')
        ->join('group_members', 
        function($join){
            $join->on('group_members.group_id', '=', 'group.id')
            ->distinct()->pluck('group_members.user_id')->count();
        })
        ->get();

which returns error

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'on group . id = group_members .`group_id

Please Help

If you've got your relationship set up in your Group model like

public function group_members()
{
    return $this->hasMany('App\GroupMember');
}

and in GroupMember model like

public function group()
{
    return $this->belongsTo('App\Group');
}

you should be able to do

$groups = Group::all();

foreach ($groups as $group) {
    $group->member_count = $group->group_members()->count();
}

$groupsArray = $groups->toArray();

Or

$group = Group::where('column', 'value')->with('group_members')->first();
$count = $group->group_members->count();

Read up on Relationships and Collections in the docs


You could also use a mutatus/accessor to return the member count as a property of the model so in your Group model

getGroupMemberCountAttribute() {
    return $this->group_members()->count();
}

And use it like

$group->group_member_count;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM