我有以下Eloquent模型:
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?)');
}}
Run Code Online (Sandbox Code Playgroud)
是否可以按"dbd"字段对"lastdate"字段进行排序:
$songs->orderBy('title', 'asc'); - works
$songs->orderBy('lastDate', 'desc'); - doesn't works
Run Code Online (Sandbox Code Playgroud)
可能存在简单的答案?
编辑:
我的数据库结构(只需要字段),多对多:
事件表
event_id
日期
歌曲表
song_id
标题
song_event数据透视表
id
song_id
event_id
SQL请求:
SELECT s.title, (SELECT MAX(e.date) FROM events e JOIN song_event se ON (e.id = se.event_id) WHERE se.song_id = …Run Code Online (Sandbox Code Playgroud)