Laravel 5.5如何使用原生SQL语句创建数据表?
Hey there! I totally get that you already have a fully formed raw SQL string for creating a table, and you're wondering how to run it within Laravel—especially with a specific database connection. Let's break down the simplest, most straightforward ways to make this work.
Method 1: Use the DB Facade's statement() Method
The easiest approach is to skip the Schema builder entirely here, since you already have your complete CREATE TABLE query. Laravel's DB facade has a statement() method designed exactly for running SQL commands that don't return results (like CREATE, ALTER, or DROP statements).
Here's how to implement it with your specific connection:
use Illuminate\Support\Facades\DB; // Your existing raw SQL string $createTableSqlString = "CREATE TABLE $newTableName ( product_id INT(11) NOT NULL AUTO_INCREMENT, ... ) COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=1;"; // Execute the raw SQL on your target connection DB::connection('mysqlInvsys')->statement($createTableSqlString);
Key Notes:
- The
statement()method handles non-query SQL operations perfectly, which is exactly what creating a table is. - By calling
connection('mysqlInvsys'), you ensure the query runs on your desired database connection—just like you intended with the Schema builder.
Important: Secure Your Table Name
If $newTableName comes from user input or an untrusted source, you need to sanitize it to avoid SQL injection risks. Since table names can't use parameter binding, you can use your connection's PDO instance to safely escape the table name:
// Get the PDO instance for your connection $pdo = DB::connection('mysqlInvsys')->getPdo(); // Escape the table name (PDO::quote adds quotes, so we strip them for valid syntax) $safeTableName = trim($pdo->quote($newTableName), "'`"); // Build your safe SQL string $createTableSqlString = "CREATE TABLE $safeTableName ( product_id INT(11) NOT NULL AUTO_INCREMENT, ... ) COLLATE='utf8_general_ci' ENGINE=InnoDB AUTO_INCREMENT=1;";
Why Not Use Schema::create()?
The Schema::create() method is great when you want to build table structures using Laravel's fluent PHP builder, but it doesn't accept raw SQL strings directly. Trying to force your existing SQL into that pattern would be unnecessary extra work—using DB::statement() is far more efficient here.
内容的提问来源于stack exchange,提问作者LakiGeri

