如何在 Laravel 中编写原始查询

How to write raw query in Laravel

我需要在 Laravel 数据库中编写一个原始查询:查询生成器,输出特定 table

的大小

核心mysql查询如下

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";

您可以在 laravel 中使用原始查询获取记录,例如:

$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);

您可以使用查询生成器,因为您可以将原始部分最小化到 table 大小:

$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();