Laravel Orderby无法在雄辩的内部工作有关系? [英] Laravel Orderby not working inside Eloquent whereHas relationship?

查看:116
本文介绍了Laravel Orderby无法在雄辩的内部工作有关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看下面的代码.

 $serviceNew = CompletedService::selectRaw('gallons_collected as total,account_id,id,service_provider_id,service_id,service_date')
            ->where("service_id", '1')->where('service_provider_id', $service_privider_id)->whereMonth('service_date', $month)->whereYear('service_date', $year)
            ->with('account')
            ->whereHas('account', function($qs) {
                $qs->orderBy('restaurant_name', 'DESC');
            })
            ->get();

我在"CompletedService"中有多个记录,并且在帐户表中有一个父ID account_id.而且我是凭帐户付款的.

I have multiple records in "CompletedService" and there is one parent id account_id which in account table. and i made with on account.

ASC和DESC已经尝试过.

Already ASC and DESC tried.

尝试在有的地方进行排序,但这对任何记录都没有影响. 下面是模型关系.

Try to order by in whereHas but it's not affect on any records. Below is model relationship.

 public function account() {
    return $this->hasOne('App\Account', 'id', 'account_id');
}

我不需要在模型中排序,因为我多次使用了此关系,并且在此单个查询中只需要排序.

i don't need to orderby in model because i used this relation in multiple time and need only order by in this single query.

并且一个完整的服务记录关系只有一个帐户. 因此,基本上我需要在帐户字段上对完成的服务记录进行排序.

And one completed service records relations have only one account. So basically i need to sort completed service records on the account field.

输出

表格

CompletedService

|id| account_id|service_id|service_provider_id|gallons_collected|service_date
|1 | 2         | 1        | 9                 | 50              | 2017-08-29

帐户

| id | restaurant_name|

每一个帮助将不胜感激. 预先谢谢.!

Every help will be appreciated. Thanks in advance.!

推荐答案

您需要为此使用替代解决方案.首先,您需要获取数据/集合,然后按以下顺序应用订单.

You need to use alternate solution for this. First you need to fetch your data/collection and then need to apply order by.

Laravel提供了一些功能,您可以使用这些功能对集合进行排序.

Laravel provides some functions, using that you can sort your collection.

https://laravel.com/docs/5.6/collections#method-sortby

使用sortByDesc(降序).所以这是您的代码:

Use sortByDesc (for descending). So here is your code :

$serviceNew = CompletedService::selectRaw('gallons_collected as total,account_id,id,service_provider_id,service_id,service_date')
            ->where("service_id", '1')->where('service_provider_id', $service_privider_id)->whereMonth('service_date', $month)->whereYear('service_date', $year)
            ->with('account')
            ->whereHas('account')
            ->get()
            ->sortByDesc('account.restaurant_name');

这篇关于Laravel Orderby无法在雄辩的内部工作有关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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