php - Laravel 将附加参数传递给 has
问题描述
假设我在这样的模型上有关系
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);
}
使用 eloquents 时如何传递参数has
。例如,这就是我想要实现的
$tenantCompany = $tenantCompany->has('currentInvoices','lastMonth');
是否可以将第二个参数传递给 eloquentshas
函数?如果没有关于我如何实现这一目标的任何建议?
解决方案
您可以使用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
推荐阅读
- c# - 获取用户头像并在 discord.net 中对其进行缩放
- android - kotlin 上 Fragment 中的 Android AdMob 自适应横幅?
- visual-studio-code - 格式 onsave 在 Prettier 的 VS Code 中不起作用
- javascript - 如何垂直居中输入字段
- java - 如何在 Android MVVM 虚拟机中建模父子关系?
- python - pygame.blit() 显示文本两次
- snowflake-cloud-data-platform - 雪花元数据:扫描字节和扫描字节
- javascript - 使用 JSON 数据禁用 onClick 事件
- javascript - Jquery-ui Sortable with js list maker from array 无法正常工作
- javascript - ReactJS CSS:“意外的令牌,预期的;”