Providing you have your relationship between posts and comments set up correctly, you can simply pass the posts.
If you are then looping through the posts using say,
foreach ($posts as $post)
then each post contains a post object and post->comments will contain a collection of comments for that post.
As collections have a count() method, you can round this off by adding
Comments ({{ $post->comments->count() }})
to your view.
petercoles said:
Providing you have your relationship between posts and comments set up correctly, you can simply pass the posts.
If you are then looping through the posts using say,
foreach ($posts as $post)
then each post contains a post object and post->comments will contain a collection of comments for that post.
As collections have a count() method, you can round this off by adding
Comments ({{ $post->comments->count() }})
to your view.
That is exactly what I'm looking for. But how do I make sure I have the correct setup?
Building the db from migrations I was unable to use foreign keys. It gave me an error I was unable to resolve.
Am I correct in assuming I need to fix my db setup to include foreign keys?
You would setup your Comments table to have a post_id column. That would be your key. Then you would setup the relationship:
// Posts model
$this->hasMany('Comment');
// Comments model
$this->belongsTo('Post');
It maybe your database doesn't support foreign keys as an index, but setting a column name with an id from the other table will be similar.
Where in the above do you point to the column post_id as being the fk we're interested in? How would it know?
protected $table = 'posts';
protected $primaryKey = 'id';
$this->hasMany('Comment');
The above gives me an error: syntax error, unexpected '$this' (T_VARIABLE), expecting function (T_FUNCTION)
It seems I just got the structure wrong. I found my answer here: http://laravel.com/docs/eloquent#one-to-many
Thank you for the help!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community