L
L
lolrofl012021-04-08 14:14:29
Web development
lolrofl01, 2021-04-08 14:14:29

How to get the number of articles for each user?

Task: display a list of users and next to the number of their publications.
I have a connection in the model with users:

public function posts()
    {
        return $this->hasMany(Post::class);
    }

But as far as I understand, it makes it possible to receive posts from only one specific user. And how to get for all at once? Is this possible with a connection? Just don't suggest cycles. 105050 extra requests to the database...

The second option, which is definitely working, is to add the number of publications for each user through join. But in this case, you don’t want to use links at all, because either already use them or make requests yourself. I don't like it when it's like this here and that way there.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2021-04-08
@lolrofl01

$users = User::with('posts')
    ->withCount('posts')
    ->get();

In template
@foreach ($users as $user)
    {{ $user->name }} {{ $user->posts_count }}
    @foreach ($user->posts as $post)
        {{ $post->title }}
    @endforeach
@endforeach

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question