Support the ongoing development of Laravel.io →
Eloquent Database
Last updated 2 years ago.
0

As far as I know, the only solution to "merge queries" is to refactor queries to query scopes:

class DeviceReport extends Model
{
    public function scopeHaveSetting($query)
    {
         return $query->whereNotNull('device_setting_id');
    }

    public function scopeHaveDeviceSetttingFor($query, $companyId)
    {
        return $query->whereHas('deviceSetting', function ($q) use ($companyId) {
            $q->where('company_id', $companyId);
        });
    }

    public function scopeHaveNoSetting($query)
    {
         return $query->whereNull('device_setting_id');
    }

    public function scopeHaveDeviceAssignmentFor($query, $companyId)
    {
        return $query->whereHas('deviceAssignment', function ($q) use ($companyId) {
            $q->where('company_id', $companyId);
        });
    }

    public function scopeQueryOne($query, $companyId = null)
    {
        return $query->where(function ($query) use ($companyId) {
            $query->haveSetting()
                ->when($company_id, function ($query) use ($companyId) {
                    return $query->haveDeviceSettingFor($companyId);
            });
        })
    }

    public function scopeQueryTwo($query, $companyId = null)
    {
        $query->where(function ($query) use ($companyId) {
                 $query->haveNoSetting()
                    ->when($company_id, function ($query) use ($companyId) {
                        return $query->haveDeviceAssignmentFor($companyId);
                     });
        });
    }
}

Then you can merge queries together like this:

return DeviceReport::where(function ($query) use ($company_id) {
    $query->haveSetting()
        ->when($company_id, function ($query) use ($company_id) {
            return $query->haveDeviceSettingFor($company_id);
        });
})->orWhere(function ($query) {
    $query->haveNoSetting()
        ->when($company_id, function ($query) use ($company_id) {
            return $query->haveDeviceAssignmentFor($company_id);
        });
})

I personally prefer the above query, it is apparently more readable to me. Still, you can merge two queries the way you want like this:

return DeviceReport::queryOne($company_id)->queryTwo($company_id);
Last updated 3 years ago.

bluepine810, selcukcukur, codekj liked this reply

3

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.