PHP Laravel如何使用两个表进行排序

时间:2019-05-06 08:02:48

标签: php mysql laravel

我的Laravel应用程序中有两个MySQL表,一个叫做categories,另一个叫做employeescategories表的结构为:

id
category
order

并且employees表还具有称为:

的列
id
category
order

因此,假设我有categories,例如:顾问,程序员和行政管理,当我在后端创建Employee时,可以将新员工分配到以下类别之一。现在,在我的Laravel应用程序的前端,我希望按类别显示雇员,并按给出的顺序显示类别。假设顾问的顺序为2,程序员的顺序为1,管理的顺序为3。

现在我的控制器如下:

use App\Employee;

class EmployeesController extends Controller
{

    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('order') as $worker)
      // content of the employee
    @endforeach
 </div>
@endforeach

这仅通过使用“雇员”表的类别即可正确地对雇员进行排序,但是如上所述,我无法按我想要的类别对类别进行排序。

那么,有人可以帮我吗?

编辑

作为示例,我希望输出看起来像这样:

Programmers (since this category has order of 1)
 // employees with category "programmers" here

Consultants (2)
 // employees with category "consultants" here

Administration (3)
 // employees with category "administration" here

2 个答案:

答案 0 :(得分:1)

对我来说,列定义有点混乱,我可以建议对列进行更改:

Table 'categories'
------------------
id
name
order

Table 'employees'
-----------------
id
category_id

将外键添加到员工表:

$table->foreign('category_id')->references('id')->on('categories')

然后可以使用关系方法将您的模型相互映射:

class Employee extends Model
{
    public function category()
    { 
        return $this->belongsTo(Category::class);
    }
}

class Category extends Model
{
    public function employees()
    { 
        return $this->hasMany(Employee::class);
    }
}

因此,我们可以通过以下方式简单地从控制器查询数据库:

use App\Category;

class EmployeesController extends Controller
{

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

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

并在刀片视图中显示结果:

@foreach ($categories as $category)
  <div class="col text-center mb-6">
    <h2>{{ $category->name }}</h2>
  </div>
  <div class="row px-4 px-xl-10">
    @foreach($category->employees as $employee)
      // content of the employee
    @endforeach
 </div>
@endforeach

答案 1 :(得分:0)

我认为您必须将查询更改为:

$categories = Category::with(['employees'=>function($q){
   $q->orderBy('order');
}])->orderBy('order')->get();
相关问题