Laravel雄辩地讲述了如何在appends数组中通过访问器对集合进行排序

Laravel雄辩地讲述了如何在appends数组中通过访问器对集合进行排序,laravel,laravel-4,eloquent,Laravel,Laravel 4,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 fun

我有以下雄辩的模型:

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ч)');
}}
是否可以按与db字段相同的“lastdate”字段进行排序:

$songs->orderBy('title', 'asc'); - works
$songs->orderBy('lastDate', 'desc'); - doesn't works
可能存在简单的答案吗

编辑:

我的数据库结构(仅需要字段),具有多对多:

事件表
事件id
日期

歌曲表
歌曲id
标题

宋_事件透视表
id
歌曲id
事件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 = s.id) AS s_date FROM mg_songs s ORDER BY s_date desc

您可以按访问器对结果集合进行排序,显然查询不能排序,因为它不在数据库中

$songs = Song::all(); // get the result
$songs->sortByDesc('lastDate'); // sort using collection method

// or ascending:
$songs->sortBy('lastDate');
如果您更愿意在db调用中执行此操作,则可以使用
连接实现相同的效果(在性能方面更好)


另一件事:您使用
if(!$this->events)
,这很快就会引起麻烦

看看这个:

// hasOne / belongsTo / morphTo etc - single relations
$model->relation; // returns related model OR null -> evaluates to false

// BUT for hasMany / belongsToMany etc - multiple results
$model->relation; // always returns a collection, even if empty, evaluates to true
因此,如果将此
更改为:

public function getLastDateAttribute()
{
    if ( ! count($this->events)) return null;

    return $this->events[0]->date->formatLocalized('%d.%m.%Y (%a, %Hч)');
}}

谢谢!你说的使用连接是什么意思?请参见上面的三个表和右SQL Request,您希望实现的具体目标是什么?我希望为它们获取带有最后日期的歌曲(来自日期为max的事件的相关记录)。然后我想按歌曲标题(没问题)和歌曲的最后日期向用户提供排序结果。在Laravel 5中,
sortBy()
返回集合的排序实例,因此您需要使用:
$songs=$songs->sortBy('lastDate')