简体   繁体   中英

Laravel relationship many to many filtering on pivot field

I have a relationship between Invoice and Shift .

Invoice model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    public $primaryKey = 'id';
    protected $fillable = [
        'user_id',
        'date_ins',
        'closeco',
        'closedrh',
        'lvl',
        'new',
    ];

    public function user()
    {
        return $this->hasOne(User::class,'id','user_id');
    }

    /**
     * The roles that belong to the invoice.
     */
    public function shifts()
    {
        return $this->belongsToMany(Shift::class, 'invoice_shift')
        ->withPivot([
            'invoice_id', 'shift_id', 'shift_taken_id', 'shift_swapped_date', 'shift_taken_date', 'tas',
            'status_tas', 'status_co', 'status_drh', 'back_co', 
            'msg', 'msg_co', 'msg_drh'
        ])
        ->orderBy('status_drh', 'ASC')
        ->orderBy('status_co', 'ASC');
    }

}

Shift model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Shift extends Model
{
    public $primaryKey = 'id';
    protected $fillable = [
        'code',
        'description',
    ];
    /**
     * The users that belong to the role.
     */
    public function invoices()
    {
        return $this->belongsToMany(Invoice::class, 'invoice_shift')
        ->orderBy('status_drh', 'ASC')
        ->orderBy('status_co', 'ASC');
    }
}

So I have a pivot table called Invoice_shift .

I cannot extract, starting from invoices table, just invoices that have tas (in invoice_shift table) = current logged user.

I cannot filter as a static value in Invoice model definition with wherepivot because it is dynamic value, every time logged user id is different.

I tried to do this in controller

 $invoices = Invoice::with('shifts.invoices')
        ->orderBy('date_ins', 'DESC')->get();

    $filter = $invoices->shifts()
    ->wherePivot('tas', '=', $user_id)
    ->get();

but I get an error because I think invoices are a collection... I tried to insert a foreach...but it doesn't work.

The error message:

Method Illuminate\Database\Eloquent\Collection::shifts does not exist

How can I do this?

Thanks

$invoices is an instance of Illuminate\Database\Eloquent\Collection and therefore relationship shifts() cannot be used..

Maybe you need the correct Eloquent builder to filter invoices using whereHas("relationship", fn)

$filteredInvoices = Invoice::with('shifts.invoices')
                       ->whereHas("shifts", function($query) use ($user_id) {
                          $query->wherePivot('tas', $user_id)
                       })
                       ->orderBy('date_ins', 'DESC')
                       ->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM