How do I know and count the number of rows in an SQL query with Laravel?

Asked

Viewed 480 times

2

 $teste = DB::table("cnaes")
                ->select("id")
                ->where("cnpj", $cnpj)
                ->where("cnae", $cnae);

How can I know how many lines were affected by this query?

3 answers

4


You can use the method count()

 $teste = DB::table("cnaes")
                ->select("id")
                ->where("cnpj", $cnpj)
                ->where("cnae", $cnae)
                ->count();

  • That settles it, thank you.

4

beauty ?

I found a little bit like the codeigniter that structure there...

In this case, the sql used is num_rows... Look in the Laravel documentation to see how it applies.

If it matches the codeigniter, it would look like this:

   $teste = DB::table("cnaes")
                    ->select("id")
                    ->where("cnpj", $cnpj)
                    ->where("cnae", $cnae);


     echo $teste->num_rows();
  • So using PDO I just used the rowCount() and solved my problem already,.

  • Use only ->Count(); after ->Where("cnae", $cnae); and remove echo.

3

The correct answer is two ways

1:

$teste = DB::table("cnaes")
                ->select("id")
                ->where("cnpj", $cnpj)
                ->where("cnae", $cnae)->get()->count();

2:

 $teste = DB::table("cnaes")
                ->select(\DB::raw("COUNT(id)" as quantidade))
                ->where("cnpj", $cnpj)
                ->where("cnae", $cnae)->get();

Take a look at the documentation that there may be ->sum() I don’t remember if there are 4 ways.

  • 1

    Hello, only Count() solves my problem, thank you very much for your help.

  • I suggest you choose an answer which has solved your doubt so you can help other people.

Browser other questions tagged

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