简体   繁体   English

PHP Laravel如何按类别排序

[英]PHP Laravel how to sort by category

I'm building a Laravel application and I have now added two tables, an "employees" and "employees_category" table. 我正在构建一个Laravel应用程序,现在添加了两个表,即“ employees”和“ employees_category”表。 Both of them have an "order" column so that I can set the order of how the categories and employees will be displayed on the website. 两者都有一个“订单”列,因此我可以设置类别和员工在网站上的显示顺序。

When I add an employee, I can assign them to a category. 添加员工时,可以将其分配到类别。 So far so good, I'm able to display the employees in order they have been set, but not the categories. 到目前为止,我可以按设置顺序显示员工,但不能显示类别。

This is what I have so far: 这是我到目前为止的内容:

My EmployeesController: 我的EmployeesController:

public function index()
{
    $employees = Employee::all()->groupBy('category');

    return view('app.employee.index', compact('employees'));
}

And in my blade view: 在我的刀片视图中:

@foreach ($employees as $category => $workers)
<div class="col text-center mb-6">
    <h2>{{ $category }}</h2>
</div>
<div class="row px-4 px-xl-10">
    @foreach($workers->sortBy('employee_order') as $worker)
      // some content
    @endforeach
</div>
@endforeach

This sorts the employees correctly by order-number but not the categories, how can I achieve that? 这样可以按订单号而不是类别正确地对员工进行排序,如何实现?

Why dont you query exactly what you want in your view 为什么不准确查询您想要的视图

public function index()
{
    $categories = Category::with('employees')->get();

    return view('app.employee.index', compact('categories'));
}

and in the view : (notice what you want is as $category => $workers ) 并在视图中:(注意,您想要的是as $category => $workers

@foreach ($categories as $category)
<div class="col text-center mb-6">
    <h2>{{ $category }}</h2>
</div>
<div class="row px-4 px-xl-10">
    @foreach($category->employees->sortBy('employee_order') as $worker)
      // some content
    @endforeach
</div>
@endforeach

The good thing is you can now paginate on the catogories 好消息是您现在可以对分类进行分页

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM