Creating MYSQL Procedure in Laravel 4 Migrations

后端 未结 2 1906
悲哀的现实
悲哀的现实 2020-12-03 11:01

Is there a way to generate stored MYSQL procedures in a Laravel 4 migration?

For example, here\'s a simple procedure generation query stored as a string (via a Hered

2条回答
  •  广开言路
    2020-12-03 11:45

    There are two major problems with your code

    1. DELIMITER is not a valid sql statement. It's just a MySql client command. So just don't use it. BTW the error you get tells you exactly that.
    2. You can't use DB::statement to execute CREATE PROCEDURE code because it uses prepared statement source code for Connection. You can use PDO exec() DB::connection()->getPdo()->exec() instead

    That being said a sample migration for imaginary tags table might look like this

    class CreateTagsTable extends Migration {
    
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('tags', function($table){
                $table->increments('id');
                $table->string('name')->unique();
            });
    $sql = <<getPdo()->exec($sql);
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            $sql = "DROP PROCEDURE IF EXISTS sp_insert_tag";
            DB::connection()->getPdo()->exec($sql);
            Schema::drop('tags');
        }
    }
    

提交回复
热议问题