Laravel按相关表格排序

问题描述 投票:7回答:3

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

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

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

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

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

这是雄辩的关系。

产品

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

类别:

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

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

而观点部分:

@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
php laravel sorting html-table
3个回答
6
投票

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

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

这应该也有效:

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

3
投票

你可以使用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();

-1
投票

在laravel中,你无法通过相关表执行订单而无需手动加入相关表,这真的很尴尬,但是这个包可以为你开箱即用https://github.com/fico7489/laravel-eloquent-join

© www.soinside.com 2019 - 2024. All rights reserved.