R
R
root092016-03-08 11:16:07
Laravel
root09, 2016-03-08 11:16:07

ORM relationship in Laravel?

There is a mini forum, you need to display the number of messages in the forum section.
I did the output of the number of topics like this:

class Forum extends Model
{
    public function topics()
    {
        return $this->hasMany('App\Topic', 'id_forum', 'id');
    }
}
....
Темы: {{$forum->topics->count()}}

How to display the number of messages?
Tried to do this, doesn't work:
class Topic extends Model
{
    public function messages()
    {
        return $this->hasMany('App\Message', 'id_topic', 'id');
    }
}
......
Сообщений: {{$forum->topics->messages->count()}}

Undefined property: Illuminate\Database\Eloquent\Collection::$messages (View: C:\OpenServer\domains\forum.local\resources\views\layouts\main.blade.php)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2016-03-08
@root09

$forum->topics is a collection of topics. Posts are tied to each specific topic, but not to their collection. Actually, that's exactly what the error says.
If you need to display the number of posts in a particular topic, then it would be something like this:

@foreach($forum->topics as $topic)
  {{ $topic->messages->count() }}
@endforeach

If you need to count the total number of posts in all topics, the collection has a sum() method .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question