Laravel 雄辩的如何通过附加数组中的访问器订购集合 [英] Laravel eloquent how to order collection by accessor in appends array

查看:20
本文介绍了Laravel 雄辩的如何通过附加数组中的访问器订购集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Eloquent 模型:

I have following Eloquent model:

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"字段进行排序:

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

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

可能存在简单的答案?

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

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

事件表
event_id
日期

events table
event_id
date

歌曲表
歌曲ID
标题

songs table
song_id
title

song_event 数据透视表
身份证
歌曲ID
event_id

song_event pivot table
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

推荐答案

可以通过访问器对结果集合进行排序,显然查询不能排序,因为它不在db中.

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');

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

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

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

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

看看这个:

// 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ч)');
}}

这篇关于Laravel 雄辩的如何通过附加数组中的访问器订购集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆