簡體   English   中英

Laravel - 檢查 pivot 表上的值的所有關系實例

[英]Laravel - Check all instances of relationship for values on pivot table

我有兩個具有多對多關系的模型,在 pivot 表上有一些附加字段:

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 中制作鏡頭,並且我想使用查詢 object 來檢查 shift_employee 上與特定班次相關的任何實例在 shift_employee 表上的hours_worked值是否大於 0。

我的第一個想法是以某種方式使用whereHas假設 Shift model 有一個關系employees ,像這樣:

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

但是......這不起作用......某些員工的輪班時間超過 0 hours_worked,這個查詢字符串對我不起作用。 我該怎么做?

首先確保您的模型正確建模。 如果是,您可以使用 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 通常在這些情況下,我使用帶有 join 的查詢圖片,我覺得這更容易

$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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM