如何在Laravel中编写原始查询

时间:2019-02-20 07:18:30

标签: mysql laravel laravel-query-builder

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

在核心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";

2 个答案:

答案 0 :(得分:2)

您可以在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);

答案 1 :(得分:2)

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

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