Laravel 排序关系

Laravel sort Relationship(Laravel 排序关系)
本文介绍了Laravel 排序关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用相关表格对结果进行排序?

How can I sort my result with related tables?

我有这个表:ClientsManagers(用户表)

I have this tables: Clients and Managers (users table)

Client.php

<?php

class Client extends Eloquent {
    protected $table = 'clients';

    public function Manager(){
        return $this->belongsTo('User','manager','id');
    }
    public function Transaction(){
        return $this->hasMany('ClientTransaction','client','id');
    }
}

Users.php(默认 Laravel 的模型)

Users.php (default Laravel's model)

我的问题是如何查询要按经理姓名排序的表客户端.

My question is how can I query table clients to be sorted by Manager's name.

到目前为止,这是我的代码:

Here is my code so far:

public function getClients() {
    // Sorting preparations
    $allowed    = array('name','contact','money');
    $sort       = in_array(Input::get('sort'), $allowed) ? Input::get('sort') : 'name';
    $order      = Input::get('order') === 'desc' ? 'desc' : 'asc';
    // Get Clients from DB
    if($sort == 'contact'){
        $clients    = Client::with(array('Manager' => function($query) use ($order) {
            $query->orderBy('name', $order);
        }));
    } else {
        $clients    = Client::orderBy($sort, $order)->with('Manager');
    }
    // Filters
    $cname      = null;
    if(Input::has('cname')){
        $clients    = $clients->where('name', Input::get('cname'));
        $cname      = '$cname='.Input::get('cname');
    }
    // Pagination
    $clients    = $clients->paginate(25);
    // Return View
    return View::make('pages.platform.clients')
        ->with('clients', $clients);
}

如果我尝试按姓名排序,它会按客户姓名排序,但如果我尝试按联系人排序,则需要按用户(经理)姓名排序.

If I try to sort by Name it sorts OK by Clients name but if I try to sort by contact it needs to sort by User's (Manager's) name.

推荐答案

试试这个.

$clients = Client::join('users as manager', 'manager.id','=','clients.manager')
            ->orderBy('manager.name', $order)
            ->select('clients.*') // avoid fetching anything from joined table
            ->with('Manager');  // if you need managers data anyway

把它放到你的 if 语句中 if($sort == 'contact'){/***

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)