首页 > 解决方案 > 如何在 Laravel 中执行 DDL 迁移脚本?

问题描述

我没有使用 Laravel 的静态类(如 DB 和 Schema),而是尝试通过读取脚本来执行完整的 DDL 脚本,然后将其执行到 MySQL 实例。

class CreateDb extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up() {
        $script = $this->readScript("create_tables.sql");
        DB::statement($script);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() {
        $script = $this->readScript("drop_table.sql");
        DB::statement($script);
    }

    /**
     * @param $str
     * @return false|string
     */
    protected function readScript($str) {
        $scripts = getcwd() . "/database/scripts/";
        $script_location = $scripts . $str;
        $myfile = fopen($script_location, "r") or die("Unable to open script file: " . $script_location);
        $script = fread($myfile, filesize($script_location));
        fclose($myfile);
        return $script;
    }
}

但是,我收到此错误:

 Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'create table if not exists comments

当我在控制台(Intellij Idea Console)中执行脚本时,它可以工作,所以我认为 Ii 可能DB::statement($script)不是完成这项工作的正确功能!

SQL 文件如下所示:

在此处输入图像描述

标签: laraveleloquent

解决方案


推荐阅读