【问题标题】:PHP Laravel how to sort by categoryPHP Laravel如何按类别排序
【发布时间】:2019-09-20 18:38:51
【问题描述】:

我正在构建一个 Laravel 应用程序,现在我添加了两个表,一个“employees”表和一个“employees_category”表。它们都有一个“顺序”列,以便我可以设置类别和员工在网站上的显示顺序。

当我添加员工时,我可以将他们分配到一个类别。到目前为止一切顺利,我能够按设置的顺序显示员工,但不能显示类别。

这是我目前所拥有的:

我的员工控制器:

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

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

在我的刀片视图中:

@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

这会按订单号而不是类别对员工进行正确排序,我该如何实现?

【问题讨论】:

  • 用户oderby查询两次
  • @st80 你发现了吗?

标签: php laravel


【解决方案1】:

你为什么不准确地查询你想要的视图

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

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

在视图中:(注意你想要的是as $category =&gt; $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

好消息是您现在可以对类别进行分页

【讨论】:

  • 这给了我:Call to undefined method Illuminate\Database\Eloquent\Builder::all()
  • 我的错,应该是get() 而不是all()
  • 嗯,好像有问题Call to undefined relationship [employees] on model
  • @ST80 在Category::class 中声明关系employees。我猜是hasMany 关系
猜你喜欢
  • 2013-07-22
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 2019-08-20
  • 2012-06-24
  • 2017-06-27
相关资源
最近更新 更多