让我们说我与这样的模型有关系
public function currentInvoices($time = 'current'){
switch ($time) {
case 'current':
$start = Carbon::create()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->endOfMonth()->format('Y-m-d H:i:s');
break;
case 'lastMonth':
$start = Carbon::create()->subMonth()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->subMonth()->endOfMonth()->format('Y-m-d H:i:s');
break;
default:
$start = Carbon::create()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->endOfMonth()->format('Y-m-d H:i:s');
}
return $this->hasManyThrough(
'App\Models\Invoices',
'App\Models\Tenancies\Tenancies',
'linked_tenant_id', // Foreign key on Tenancies table...
'tenant_id', // Foreign key on invoices table...
'id', // Local key on tenants table...
'id' // Local key on tenancies table...
)->where('invoices.start_date','>=',$start)->where('invoices.end_date','<=',$end);
}
使用口才has
时如何传递参数。例如,这就是我要实现的目标
$tenantCompany = $tenantCompany->has('currentInvoices','lastMonth');
是否可以将第二个参数传递给雄辩的has
函数?如果没有关于如何实现此目标的建议?
答案 0 :(得分:1)
您可以使用whereHas
$tenantCompany = $tenantCompany->whereHas('currentInvoices', function($query) use($start_date, $end_date {
$query->where('start_date', '>=', $start_date)->where('end_date', '<=', $end_date);
})->get();
有关关系方法的更多信息:https://laravel.com/docs/5.6/eloquent-relationships
答案 1 :(得分:0)
我更喜欢这样
public function invoices(){
return $this->hasManyThrough(
'App\Models\Invoices',
'App\Models\Tenancies\Tenancies',
'linked_tenant_id', // Foreign key on Tenancies table...
'tenant_id', // Foreign key on invoices table...
'id', // Local key on tenants table...
'id' // Local key on tenancies table...
);
}
public function currentInvoices(){
$start = Carbon::create()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->endOfMonth()->format('Y-m-d H:i:s');
return $this->invoices()->where('invoices.start_date','>=',$start)
->where('invoices.end_date','<=',$end);
}
public function lastMonthInvoices(){
$start = Carbon::create()->subMonth()->startOfMonth()->format('Y-m-d H:i:s');
$end = Carbon::create()->subMonth()->endOfMonth()->format('Y-m-d H:i:s');
return $this->invoices()->where('invoices.start_date','>=',$start)
->where('invoices.end_date','<=',$end);
}
现在这样获取
$tenantCompany = $tenantCompany->has('lastMonthInvoices');