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";
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();
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.
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.
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.
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);
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With