I have following Eloquent model:
class Song extends Eloquent {
protected $table = 'mg_songs';
protected $hidden = array('events');
protected $appends = array('lastDate');
public function events()
{
return $this->belongsToMany('Event', 'song_event');
}
public function getLastDateAttribute()
{
if (!$this->events) return null;
return $this->events[0]->date->formatLocalized('%d.%m.%Y (%a, %Hч)');
}}
Is it possible to sort by "lastdate" field same as db field:
$songs->orderBy('title', 'asc'); - works
$songs->orderBy('lastDate', 'desc'); - doesn't works
May be exist simple answer?
EDITED:
My db structure (only needed fields), with many-to-many:
events table
event_id
date
songs table
song_id
title
song_event pivot table
id
song_id
event_id
SQL-request:
SELECT s.title, (SELECT MAX(e.date) FROM events e JOIN song_event se ON (e.id = se.event_id) WHERE se.song_id = s.id) AS s_date FROM mg_songs s ORDER BY s_date desc