我有这个数据库结构
table users table office_user table offices
----------- ----------------- -------------
id * id * id *
full_name user_id name
office_id
joined_at因此,在我的项目中,每个office都有许多用户,用户可以在日期上加入多个office (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字段在枢轴表中对他们进行统计。
谢谢你,对不起我的英语
发布于 2019-04-01 17:36:18
但结果并不像预期的那样,它给了我所有的用户在某些办公室和他们的计数,无论有联合日期。
当您执行$office->users->count()时,这是预期的行为,因为您在任何时候都要检索每个office的所有相关users,因此,如果您返回了所有这些用户,那么在集合中执行的count()将对所有用户进行计数。
您的透视属性只是一个timestamp,那么如何减少返回的用户数量呢?今天/在最后一小时/在过去15分钟内加入办公室的用户?
如果是这样,可以向count()方法中添加约束,以获得所需的结果。
例如,在下面的行中,我们将约束具有当前属于joined_at的关联办公室:
public function show(Office $office)
{
$users = User::with([
'phones',
'offices' => function ($offices) {
$offices->whereDate('joined_at', '>', now()->startOfDay());
},
])->get();
return view('dashboard.offices.show', compact([office, 'users']));
}检查文档的本节:
约束期望载荷 有时,您可能希望加载关系,但也希望为急切加载查询指定额外的查询条件。下面是一个例子: $users =App\User::with(‘post’=>函数($query) { $query->where('title','like','%first%');})->get(); 在本例中,雄辩者只会在post的
title列包含单词first的情况下才会急切地加载帖子。您可以调用其他查询生成器方法来进一步自定义急切的加载操作: $users =App\User::with(‘post’=> function ($query) { $query->orderBy('created_at','desc');})->get();
https://stackoverflow.com/questions/55460256
复制相似问题