首页 > 解决方案 > 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函数?如果没有关于我如何实现这一目标的任何建议?

标签: phplaravellaravel-5eloquent

解决方案


您可以使用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


推荐阅读