Laravel 按相关表排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36856918/
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 13:41:11  来源:igfitidea点击:

Laravel order by related table

phplaravelsortinghtml-table

提问by Norgul

I have Product and Category models in my project. Product belongs to Category. Since Product has foreign key category_id, I could easily sort the output like so:

我的项目中有产品和类别模型。产品属于类别。由于产品具有外键 category_id,我可以轻松地对输出进行排序,如下所示:

$products = Product::orderBy('category_id', 'asc')->get();

But what I really wanted is to sort Products by Category name, so I tried:

但我真正想要的是按类别名称对产品进行排序,所以我尝试了:

$products = Product::with(['categories' => function($q){
            $q->orderBy('name', 'asc')->first();
        }]);

But that outputs nothing. As a test, I have returned return Product::with('categories')->first();and it outputs fine...

但这没有任何输出。作为测试,我已经返回return Product::with('categories')->first();并且输出正常......

Here are the Eloquent relations.

这里是雄辩的关系。

Product

产品

class Product extends Model
{
    protected $fillable = [
        'name',
        'description',
        'price',
        'category_id',
    ];

    protected $hidden = [
        'created_at',
        'updated_at',
    ];

    public function categories()
    {
        return $this->belongsTo('\App\Category', 'category_id');
    }
}

Category:

类别:

class Category extends Model
{
    protected $fillable = [
        'name'
    ];

    public function products()
    {
        return $this->hasMany('\App\Product');
    }
}

And the view part:

和视图部分:

@foreach ($products as $product)
                <tr>

                    <td>{!! $product->categories->name !!}</td>
                    <td>
                        @if(!empty($product->picture))
                            Yes
                        @else
                            No
                        @endif
                    </td>
                    <td>{!! $product->name !!}</td>
                    <td>{!! $product->description !!}</td>
                    <td>{!! $product->price !!}</td>
                    <td>
                        <a href="{{ url('/product/'.$product->id.'/edit') }}">
                            <i class="fa fa-fw fa-pencil text-warning"></i>
                        </a>
                        <a href="" data-href="{{route('product.destroyMe', $product->id)}}"
                           data-toggle="modal" data-target="#confirm-delete">
                            <i class="fa fa-fw fa-times text-danger"></i>
                        </a>
                    </td>
                </tr>
            @endforeach

采纳答案by geckob

I have not tested this, but I think this should work

我没有测试过这个,但我认为这应该有效

// Get all the products
$products = \App\Product::all();

// Add Closure function to the sortBy method, to sort by the name of the category
$products->sortBy(function($product) { 
  return $product->categories()->name;
});

This should also working:

这也应该有效:

 $products = Product::with('categories')->get()
   ->sortBy(function($product) { 
       return $product->categories->name;
  })

回答by DsRaj

You can use join(), try below code

你可以使用join(),试试下面的代码

$query = new Product; //new object
//$query = Product::where('id','!=',0);
$query = $query->join('categories', 'categories.id','=','products.categories.id');
$query = $query->select('categories.name as cat_name','products.*');
$query = $query->orderBy('cat_name','asc');
$record = $query->get();

回答by fico7489

In laravel, you can't perform order by related table without manually joining related table what is really very awkward, but this can package can do this for you out of the box https://github.com/fico7489/laravel-eloquent-join

在laravel中,你不能在不手动加入相关表的情况下按相关表执行排序,这真的很尴尬,但是这个可以打包为你开箱即用的https://github.com/fico7489/laravel-eloquent-加入