【发布时间】:2021-08-12 16:59:34
【问题描述】:
我在Invoice 和Shift 之间有关系。
发票模型
<?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型号
<?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');
}
}
所以我有一个名为 Invoice_shift 的数据透视表。
我无法从 invoices 表开始提取具有 tas(invoice_shift 表中)= 当前登录用户的发票。
我无法使用 wherepivot 在 Invoice 模型定义中过滤为静态值,因为它是动态值,每次登录的用户 ID 都不同。
我尝试在控制器中执行此操作
$invoices = Invoice::with('shifts.invoices')
->orderBy('date_ins', 'DESC')->get();
$filter = $invoices->shifts()
->wherePivot('tas', '=', $user_id)
->get();
但我收到一个错误,因为我认为发票是一个集合...我尝试插入一个 foreach...但它不起作用。
错误信息:
方法 Illuminate\Database\Eloquent\Collection::shifts 不存在
我该怎么做?
谢谢
【问题讨论】:
-
您能否在帖子中添加您遇到的错误?
-
消息:“方法 Illuminate\\Database\\Eloquent\\Collection::shifts 不存在。”