Carry out two consultations in the same method in Laravel

0

In an application made with Laravel, I have the following methods:

public function scopeGetCountAndSumCotizacionesByVendedor($query, $ano, $mes)
{        
    return $query->select('trabajada_por', DB::raw('COUNT("trabajada_por") as cant_vendedor'), DB::raw('SUM("monto") as total'))
                    ->where('nombre_status', 'LIKE' ,'COT%')
                    ->where('borrado', 0)
                    ->whereYear('fecha_recibido', $ano)
                    ->whereMonth('fecha_recibido', $mes)
                    ->groupBy('trabajada_por')
                    ->get();
}
public function scopeGetCountAndSumCotizacionesByVendedorByTemporada($query, $ano, $mes_desde, $mes_hasta)
{        
    return $query->select('trabajada_por', DB::raw('COUNT("trabajada_por") as cant_vendedor'), DB::raw('SUM("monto") as total'))
                    ->where('nombre_status', 'LIKE' ,'COT%')
                    ->where('borrado', 0)
                    ->whereYear('fecha_recibido', $ano)
                    ->whereMonth('fecha_recibido', '>=', $mes_desde)
                    ->whereMonth('fecha_recibido', '<=', $mes_hasta)
                    ->groupBy('trabajada_por')
                    ->get(); 
}

And I call from the controller:

I call the method when I only need the data for a single month.

$cotizacionesCantPorVendedor = Cotizaciones::getCountAndSumCotizacionesByVendedor($ano, $mes);

I call this other method when I have to bring data between a range of months.

$cotizacionesCantPorVendedorPorTemporada = Cotizaciones::getCountAndSumCotizacionesAByVendedorByTemporada($ano, $mes_desde, $mes_hasta);

As you can see, most of the body of the methods are the same, just change the whereMonth by the range of months or a particular month. I would like to know if you can perform these same queries in a single method in the cleanest way possible, so do not use two different methods and be able to save much more code.

    
asked by fed R 06.01.2018 в 03:42
source

1 answer

2
public function scopeGetCountAndSumCotizacionesByVendedorByTemporada($query, $ano, $mes_desde, $mes_hasta)
{
        return $query
            ->select('trabajada_por', DB::raw('COUNT("trabajada_por") as cant_vendedor'), DB::raw('SUM("monto") as total'))
            ->where('nombre_status', 'LIKE', 'COT%')
            ->where('borrado', 0)
            ->whereYear('fecha_recibido', $ano)
            ->whereBetween('fecha_recibido', [$mes_desde, $mes_hasta])
            ->groupBy('trabajada_por')
            ->get();
}

You spend it in $ month_from the start month and $ month_until the final month, and when you want just one month you spend the same month in each variable

    
answered by 11.01.2018 / 17:04
source