【问题标题】:Laravel - Check all instances of relationship for values on pivot tableLaravel - 检查数据透视表上的值的所有关系实例
【发布时间】:2021-04-27 15:56:20
【问题描述】:

我有两个具有多对多关系的模型,在数据透视表上有一些附加字段:

Shift table:
------------
id - uuid
date - date
address - string
...

Employee table:
---------------
id - uuid
first_name - string
...

shift_employee table:
---------------------
id - integer
shift_id - uuid
employee_id - uuid
hours_worked - integer
...

现在,我正在 Laravel Nova 中制作一个镜头,我想使用查询对象来检查 shift_employee 上与特定班次相关的任何实例的 hours_worked 值是否大于 0 em> 在 shift_employee 表上。

我的第一个想法是以某种方式使用 whereHas 假设 Shift 模型具有关系 employees,如下所示:

$query->whereHas('employees' function ($q) {
    $q->where('hours_worked', '>', 0);
});

但是...这不起作用...某些员工的轮班时间超过 0 hours_worked 并且此查询字符串对我不起作用。我该怎么做?

【问题讨论】:

  • this 回答你的问题了吗?
  • 不,不是
  • 据我了解,您处于轮班资源模型中,您只想获得工作时间超过 0 小时的员工,对吗?你能给我们你得到的结果和你想要的结果吗?

标签: php laravel laravel-nova


【解决方案1】:

首先确保您的模型建模正确。如果是,您可以使用如下所示的 pivot 属性访问中间表的任何属性:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    /**
     * The users that belong to the role.
     */
    public function users()
    {
        return $this->belongsToMany('App\User');
    }
}

示例:

$user = App\User::find(1);

foreach ($user->roles as $role) {
    echo $role->pivot->created_at;
}

在你的情况下,试试:

$employee = Employee::with('Shift');

foreach($employee as $e){
     $employeeHw[] = $e->shift_employee->where('hours_worked', '>', 0)->get();
}

我也是 laverel 的新手,所以我不确定它是否有效,但理论上:P 通常在这些情况下,我会使用带有连接的查询图片,我觉得更容易

$users = DB::table('users')
        ->join('contacts', 'users.id', '=', 'contacts.user_id')
        ->join('orders', 'users.id', '=', 'orders.user_id')
        ->select('users.*', 'contacts.phone', 'orders.price')
        ->get();

【讨论】:

    猜你喜欢
    • 2017-07-22
    • 2020-08-22
    • 2014-08-26
    • 1970-01-01
    • 2019-08-21
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多