Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write raw query in Laravel

I need to write a raw query in Laravel Database: Query Builder, That outputs size of specific table

In core mysql query is as following

SELECT table_name "Name_of_the_table", table_rows "Rows Count", round(((data_length + index_length)/1024/1024),2)
"Table Size (MB)" FROM information_schema.TABLES WHERE table_schema = "Name_of_the_Database" AND table_name ="Name_of_the_table";
like image 315
Hemant Maurya Avatar asked Feb 20 '19 07:02

Hemant Maurya


People also ask

How get raw SQL query in Laravel?

Get raw SQL output of a query. The easiest way to get the raw SQL output of this query, is by using the toSql() method: use App\User; User::whereHas( 'orders. payments',fn ($q) => $q->where('amount', '>', 400) )->toSql();

What is DB :: Raw in Laravel?

DB::raw() is used to make arbitrary SQL commands which aren't parsed any further by the query builder. They therefore can create a vector for attack via SQL injection.

What is raw query?

On the other hand, RawQuery serves as an escape hatch where you can build your own SQL query at runtime but still use Room to convert it into objects. RawQuery methods must return a non-void type. If you want to execute a raw query that does not return any value, use RoomDatabase#query methods.

What is query () in Laravel?

In Laravel the database query builder provides an easy interface to create and run database queries. It can be used to perform all the database operations in your application, from basic DB Connection, CRUD, Aggregates, etc. and it works on all supported database systems like a champ.


2 Answers

You can get records by using raw query in laravel like:

$sql = 'SELECT table_name "Name_of_the_table", table_rows "Rows Count", round(((data_length + index_length)/1024/1024),2)
"Table Size (MB)" FROM information_schema.TABLES WHERE table_schema = "Name_of_the_Database" AND table_name ="Name_of_the_table"';

$results = DB::select($sql);
like image 57
Abdulrehman Sheikh Avatar answered Sep 20 '22 17:09

Abdulrehman Sheikh


You can use the query builder, since you can minimize the raw part to the table size:

$data = DB::table('information_schema.TABLES')
    ->where('table_schema', 'Name_of_the_Database')
    ->where('table_name', 'Name_of_the_table')
    ->select(
        'table_name as "Name_of_the_table"',
        'table_rows as "Rows Count"',
         DB::raw('round(((data_length + index_length)/1024/1024),2) as "Table Size (MB)"')
    )
    ->first();
like image 21
Paul Spiegel Avatar answered Sep 20 '22 17:09

Paul Spiegel