Reputation: 663
I have a Conversation model with a hasMany('App\Message') relationship. I want to group all messages by the "created_at" property. So when i do:
$conversation = Conversation::first()->with('messages');
It should return something like this:
{
"conversation_name": "some conversation",
"users": [list of users in the conversation],
"messages": [
"today": [collection of messages from today],
"yesterday": [collection of messages from yesterday],
"some date": [collection of messages from some date].... etc
]
}
So far, the best i have been able to do is:
Message::all()->groupBy(function($query){
return $query->created_at->format('Y-m-d');
});
But then i only get the messages and not the rest of the conversation information. I would like to be able to do something like this:
Conversation::find(12)->with('messages')->groupBy(function($query){
return $query->created_at->format('Y-m-d');
});
But it doesn't work.
Anyone have a take on this? :)
Upvotes: 1
Views: 1199
Reputation: 663
If anyone is interested, i fixed the problem like this:
class Conversation{
protected $appends = ['messages'];
public function getMessagesAttribute(){
return Message::where('conversation_id', $this->id)
->get()->groupBy(function($query){
return $query->created_at->format('Y-m-d');
});
}
}
Upvotes: 2