-1

I need count sent emails in a month, and the last sent to everyone. I imagine something like this:

$mes=8; // or any month
$search= [100,101,102,103]; // dni
$sql = "
SELECT A.dni, $mes AS mes, COUNT(*) AS total, B.lastet_date 
FROM emails AS A
LEFT JOIN (
          SELECT dni, MAX(date_sended) AS lastet_date
          FROM emails 
          GROUP BY dni
          ) AS B
          ON B.dni = A.dni 
WHERE MONTH(date_sended) = $mes 
AND A.dni IN ('".implode("', '",$search)."') 
GROUP BY A.dni";

How can I execute it, simply, using raw method or similar?

Luciano
  • 2,052
  • 1
  • 16
  • 26
Mauricio
  • 23
  • 7

1 Answers1

1

You can use the DB::select helper:

use Illuminate\Support\Facades\DB;
...
$results = DB::select($sql)

This will return a collection where each element is a row of the query result.

NerdOfLinux
  • 1,017
  • 10
  • 24
  • 1
    Don't forget to add bindings for the `$mes` variable and `$search` list – Tony Oct 20 '21 at 23:22
  • Perfect!! I was having trouble using raw methods, or extra result when I extend class Model on my own classModelProyect. But...making sql direct on DB the result is like I hope. Thanks Nerd!!! I am new on Laravel and I didnt know what else to try. – Mauricio Oct 22 '21 at 00:41