【问题标题】:Laravel eloquent how to order collection by accessor in appends arrayLaravel 雄辩的如何通过附加数组中的访问器订购集合
【发布时间】:2014-09-22 13:38:06
【问题描述】:

我有以下 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ч)');
}}

是否可以按与db字段相同的“lastdate”字段进行排序:

$songs->orderBy('title', 'asc'); - works
$songs->orderBy('lastDate', 'desc'); - doesn't works

可能存在简单的答案?

已编辑:

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

事件表
event_id
日期

歌曲表
歌曲ID
标题

song_event 数据透视表
身份证
歌曲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

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

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

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

    如果您更喜欢在 db 调用中执行此操作,您可以使用 joins 实现相同的效果(在性能方面更好)。


    另外一件事:你使用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
    

    所以把这个if改成:

    public function getLastDateAttribute()
    {
        if ( ! count($this->events)) return null;
    
        return $this->events[0]->date->formatLocalized('%d.%m.%Y (%a, %Hч)');
    }}
    

    【讨论】:

    • 非常感谢!和你的意思是相同的使用连接?见上图,三个表和正确的 SQL 请求
    • 你到底想达到什么目的?
    • 我想为他们获取最后日期的歌曲(日期为最大值的事件的相关记录)。然后我想按主打歌(没问题)和歌曲的最后日期向用户提供排序结果。
    • 在 Laravel 5 中,sortBy() 返回集合的排序实例,因此您需要使用:$songs = $songs->sortBy('lastDate');
    猜你喜欢
    • 2015-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-05-31
    • 2017-06-17
    • 2015-08-20
    • 2015-08-15
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多