Laravel 雄辩地如何通过追加数组中的访问器对集合进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25975542/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:08:42  来源:igfitidea点击:

Laravel eloquent how to order collection by accessor in appends array

laravellaravel-4eloquent

提问by gurkov

I have following Eloquent model:

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

Is it possible to sort by "lastdate" field same as db field:

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

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

May be exist simple answer?

可能存在简单的答案?

EDITED:

编辑:

My db structure (only needed fields), with many-to-many:

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

events table
event_id
date

事件表
event_id
日期

songs table
song_id
title

歌曲表
song_id
标题

song_event pivot table
id
song_id
event_id

song_event 数据透视表
id
song_id
event_id

SQL-request:

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

回答by Jarek Tkaczyk

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).

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



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

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

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 ifto:

所以把它改成if

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

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