【发布时间】:2019-04-02 01:36:18
【问题描述】:
我有这个数据库结构
table users table office_user table offices
----------- ----------------- -------------
id * id * id *
full_name user_id name
office_id
joined_at
所以在我的项目中,每个办公室都有很多用户,并且用户可以在日期 (joined_at) 加入多个办公室
User.php 模型
public function offices()
{
return $this->belongsToMany('App\Office)->withPivot('joined_at');
}
Office.php 模型
public function users()
{
return $this->belongsToMany('App\User)->withPivot('joined_at');
}
OfficeController.php
public function show(Office $office)
{
$users = User::with(array('phones', 'offices' , function($query)
{
$query->orderBy('joined_at', 'desc');
}))->get();
return view('dashboard.offices.show', compact(['office', 'users']));
}
我需要两件事:
1- 获取每个办公室的当前用户列表
2- 每个办公室的当前用户计数
我已经做到了:
<h3>{{ $office->name }}</h3><span>{{ $office->users->count() }}</span>
@foreach ($office->users as $user)
<li>{{ $user->full_name }}</li>
@endforeach
但结果并不像预期的那样,它为我提供了某个办公室的所有用户,并且无论加入日期如何
我想要这个办公室的最后加入用户的列表,并根据数据透视表中的joined_at 字段对他们进行计数
谢谢你,对不起我的英语
【问题讨论】: