Laravel 4 Eloquent group by relationship date
I have a topics and links tables on Laravel 4.2 with Eloquent ORM. They have a relationship like this;
Topic model:
class Topic extends \Eloquent {
public function links()
{
return $this->belongsToMany('Link');
}
}
Link model:
class Link extends \Eloquent {
public function topics()
{
return $this->belongsToMany('Topic');
}
}
I want to group links like this;
05.02.2015
First Topic
- Sample link
- Sample link
Second Topic
- Sample link
- Sample link
04.02.2015
First Topic
- Sample link
- Sample link
Second Topic
- Sample link
- Sample link
Database scheme
topics
- id
- name
- created_at
- updated_at
links
- id
- title
- created_at
- updated_at
link_topic
How can I do this? I didn't solve this problem.
Thanks.
You have to group the topics collection.
$topics_collection = Topic::all();
$topics_groups = $topics_collection->groupBy('created_at');
@foreach($topics_groups as $date => $topics)
{{ $date }}
@foreach($topics as $topic)
{{ $topic->name }}
@foreach($topic->links as $link)
{{ $link->title }}
@endforeach
@endforeach
@endforeach
Not sure but I think the date here will be a timestamp. You may use https://github.com/briannesbitt/Carbon to format it like any other date in laravel.
@tgezginis You should've added, that you want to group by the date on link, correct? Or maybe date from the pivot table.. Be specific.
Oh, and btw show the result you expect in a more detailed manner. Now, being the relation m-m it's rather hard to guess what you need exactly.
@pmall it works. I added only last_link_update column to topics table and I group by this column. Thanks ;)
@tgezginis I think you can use the touch method to update the updated_at column of the parent model. So no need for an additional column ;)
http://laravel.com/docs/4.2/eloquent#insert-update-delete
Updating Only The Model's Timestamps If you wish to simply update the timestamps on a model, you may use the touch method:
$user->touch();
Please or to participate in this conversation.