Laravel 5.8-如何排序(orderBy)多重关系 [英] Laravel 5.8 - How sort (orderBy) multiple relationship

查看:112
本文介绍了Laravel 5.8-如何排序(orderBy)多重关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按视频观看次数对序列进行排序.

I am trying to sort the serials by video views.

关系:序列号与序列号具有hasMany关系.系列与剧集有hasMany关系.情节与视频具有hasOne关系.该视频与观看次数具有hasMany关系.

Relations: The Serial has a hasMany relationship to series. The Series has a hasMany relationship to episodes. The Episodes has a hasOne relationship to video. The Video has a hasMany relationship to viewcounts.

<?php
//sort method:
public function mostPopular()
    {

        $serials = Serial::with(['series.episodes.video' => function ($query) {
            $query->withCount(['videoViews' => function($query) {
            }])->orderBy('video_views_count', 'desc');
        }])->get();

        return $serials;
}

//Serial model:
public function series()
{
   return $this->hasMany(Series::class);
}


//Series model:
public function episodes()
{
   return $this->hasMany(Episode::class);
}

public function serial()
{
   return $this->belongsTo(Serial::class);
}

//Episode model:
public function video()
{
   return $this->hasOne(Video::class);
}

public function series()
{
   return $this->belongsTo(Series::class);
}

//Video model:
public function videoViews()
{
   return $this->hasMany(VideoView::class);
}

public function episode()
{
   return $this->belongsTo(Episode::class);
}


?>

我希望按视频视图(series.episodes.video.videoViews)排序的序列,但实际输出未排序.

I expect the sorted serials by video views (series.episodes.video.videoViews), but the actual output is not sorted.

Laravel 5.8PHP 7

Laravel 5.8 PHP 7

推荐答案

这实际上是一个愚蠢的做法,但我了解到实际上-可能没有多个解决方法,而是可以对collections进行多个-> sortBy排序.只是您需要颠倒它们的顺序.因此,要对带有专辑标题的艺术家目录进行排序,这就是解决方案...

This is a silly one actually but I've learnt that multiple ->sortBy on collections actually are possible with no workarounds. It's just that you need to reverse the order of them. So, to sort a catalogue of artists with their album titles this would be the solution...

而不是:

$collection->sortBy('artist')->sortBy('title');

执行此操作:

$collection->sortBy('title')->sortBy('artist');

这篇关于Laravel 5.8-如何排序(orderBy)多重关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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