【问题标题】:Laravel - Displaying fields with many to many relationship according field in pivot tableLaravel - 根据数据透视表中的字段显示具有多对多关系的字段
【发布时间】: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 字段对他们进行计数

谢谢你,对不起我的英语

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    但结果并不像预期的那样,它为我提供了某个办公室的所有用户,并且无论加入日期如何

    当您执行$office-&gt;users-&gt;count() 时,这是预期的行为,因为您会随时检索每个办公室的所有关联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']));
    }
    

    查看this section的文档:

    约束急切负载

    有时您可能希望预先加载关系,但还需要指定 急切加载查询的附加查询条件。这是一个 示例:

    $users = App\User::with(['posts' => function ($query) {
        $query->where('title', 'like', '%first%');
    }])->get();
    

    在这个例子中,Eloquent 只会预先加载帖子所在位置的帖子 title 列包含单词 first。您可以调用其他查询 构建器方法来进一步自定义急切加载操作:

    $users = App\User::with(['posts' => function ($query) {
        $query->orderBy('created_at', 'desc');
    }])->get();
    

    【讨论】:

    • 我不想要特定日期的用户 .. 我只想要现在属于办公室的用户…例如 .. 如果用户 'jack' 在 1/1 加入办公室 1 /2019 并让它在 2019 年 5 月 5 日加入办公室 2 .. 并在 2019 年 6 月 6 日回到办公室 1 .. 当我列出办公室 1 中的所有用户时,我希望用户显示的用户代表他当前的位置而不是我现在得到的两倍.. 办公室 1 中的计数用户是我得到的一个而不是两个.. 我想我必须使用 first 但不知道如何.. 希望它很清楚.. 谢谢你的时间
    猜你喜欢
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2019-10-06
    • 1970-01-01
    • 2019-08-22
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多