首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Laravel -检查枢轴表中值的所有关系实例

Laravel -检查枢轴表中值的所有关系实例
EN

Stack Overflow用户
提问于 2021-04-27 15:56:20
回答 1查看 88关注 0票数 0

我有两个具有多到多关系的模型,在枢轴表上有一些附加字段:

代码语言:javascript
复制
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中制作一个透镜,我想使用查询对象来检查shift_employee上任何与特定移位相关的实例,对于shift_employee表中的hours_worked,其值是否大于0。

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

代码语言:javascript
复制
$query->whereHas('employees' function ($q) {
    $q->where('hours_worked', '>', 0);
});

但是..。这不管用..。对于某些员工,有超过0 hours_worked的轮班,这个查询字符串不适用于我。我该怎么做?

EN

回答 1

Stack Overflow用户

发布于 2021-04-27 21:43:40

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

代码语言:javascript
复制
<?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');
    }
}

例:

代码语言:javascript
复制
$user = App\User::find(1);

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

在你的例子中,试着:

代码语言:javascript
复制
$employee = Employee::with('Shift');

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

我对laverel也很陌生,所以我不确定它是否有效,但理论上:P--通常在这些情况下,我使用的是查询bilder和join,我觉得这更容易

代码语言:javascript
复制
$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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67286546

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档