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);
bluepine810, selcukcukur, codekj liked this reply
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community