Create query in query Builder - Standard

Asked

Viewed 119 times

0

I’m starting to work with Laravel and need to make a query in the database, is a simple query, but as I’m starting I do not know yet perform it.

I need to get the sales done today, yesterday, this month, previous month, current year and previous year, but at first I need to make this query work on Laravel, more specifically using the query Builder.

SELECT 
    SUM(TotalVenda) as TotalVenda 
FROM vendas 
WHERE DATE(dtRegistro) = CURDATE()

I’m having difficulty joining the syntax instructions, for example:

$datas = DB::table('vendas')
    ->whereDate('dtRegistro', Carbon::now()->format('m/d/Y'))
    ->get();

After that I need to take the sum of the obtained result, but in this same example it no longer returns the expected that would be the records of today’s date.

  • Good morning Alan. Already took a look at documentation? Which part you’re not getting through?

  • Good morning, I’m having difficulty joining the syntax instructions, for example: $datas = DB::table('vendas')->whereDate('dtRegistro', Carbon::now()->format('m/d/Y'))->get(); .

1 answer

0


I managed to solve, it would have to be done with whereRaw, to bring the query I had done in SQL to Laravel.

$total_hoje = Vendas::whereRaw('date(DataEmissao)=date(NOW())')
                                        ->whereIn('tipo', ['Devolução', 'Pedido de venda', 'Troca'])
                                        ->sum('totalvenda');

$total_ontem = Vendas::whereRaw('date(DataEmissao)=date(DATE_ADD(now(), INTERVAL -1 DAY))')
                                        ->whereIn('tipo', ['Devolução', 'Pedido de venda', 'Troca'])
                                        ->sum('totalvenda');
  • You can mark your answer as the one that solves your doubt

Browser other questions tagged

You are not signed in. Login or sign up in order to post.