mark
mark

Reputation: 121

laravel 5.6 how to get the number of msgs for all groups?

I have 3 tables: users, groups, messages;

user table is the default table generated by php artisan make:auth, Groups table contain:

id, book_id

messages table contain:

id, group_id, from, msg_content

and there is many to many relation between users table and groups table, the pivot table conatain:

user_id, group_id, last_id_seen

now I want to get the groups that belongs to the user and the number of messages that belongs to each group and have id > last_id_seen in the following form:

group => number_of_messages_>_last_id_seen

I am new to Laravel so would you please help me to do this?

Upvotes: 0

Views: 46

Answers (1)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

Use withCount():

$groups = Auth::user()->groups()->withCount(['messages' => function($query) {
    $query->whereColumn('id', '>', 'last_id_seen');
}])->get();

foreach($groups as $group) {
    // $group->messages_count
}

Upvotes: 0

Related Questions