Laravel eloquent how to order collection by accessor in appends array

后端 未结 1 1320
鱼传尺愫
鱼传尺愫 2020-12-19 09:33

I have following Eloquent model:

class Song extends Eloquent {

protected $table = \'mg_songs\';
protected $hidden = array(\'events\');
protected $appends =          


        
相关标签:
1条回答
  • 2020-12-19 10:18

    You can sort the resulting collection by accessor, obviously the query can't be ordered, for it's not in the db.

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

    You could achieve the same using joins, if you prefer to do this in the db call (it's better in terms of performance).


    Another thing: you use if( ! $this->events) which will cause trouble soon.

    Check this out:

    // 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
    

    So change this if to:

    public function getLastDateAttribute()
    {
        if ( ! count($this->events)) return null;
    
        return $this->events[0]->date->formatLocalized('%d.%m.%Y (%a, %Hч)');
    }}
    
    0 讨论(0)
提交回复
热议问题