Laravel雄辩地说明如何通过附加数组来访问附件

gur*_*kov 6 laravel eloquent 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 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 = s.id) AS s_date FROM mg_songs s ORDER BY s_date desc
Run Code Online (Sandbox Code Playgroud)

Jar*_*zyk 17

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

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

// or ascending:
$songs->sortBy('lastDate');
Run Code Online (Sandbox Code Playgroud)

joins如果您希望在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
Run Code Online (Sandbox Code Playgroud)

所以改成这个if:

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

    return $this->events[0]->date->formatLocalized('%d.%m.%Y (%a, %H?)');
}}
Run Code Online (Sandbox Code Playgroud)