Laravel - 根据数据透视表中的字段显示具有多对多关系的字段

问题描述 投票:1回答:1

我有这个数据库结构

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字段计算它们

谢谢你,对不起我的英文

php laravel
1个回答
1
投票

但结果并不像预期的那样,它给了我某些办公室的所有用户,并且无论是否加入日期,都会计算他们

当你执行$office->users->count()这是预期的行为,因为你随时检索每个办公室的所有关联的users,所以假设你返回了所有这些用户,那么在集合中执行的count()将计算所有这些。

您的pivot属性只是一个timestamp,那么如何减少返回的用户数量?今天/最后一小时/最后15分钟加入办公室的用户可能吗?

如果是这样,您可以为qazxsw poi方法添加约束以获得所需的结果。

作为一个例子,在以下几行中,我们将约束具有属于今天的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'])); }

限制急切负荷

有时您可能希望加载关系,但也为热切加载查询指定其他查询条件。这是一个例子:

this section

在这个例子中,Eloquent只会急切地加载post的$users = App\User::with(['posts' => function ($query) { $query->where('title', 'like', '%first%'); }])->get(); 列包含单词title的帖子。您可以调用其他查询构建器方法来进一步自定义预先加载操作:

first
© www.soinside.com 2019 - 2024. All rights reserved.