在Laravel 4迁移中创建MYSQL过程 [英] Creating MYSQL Procedure in Laravel 4 Migrations
本文介绍了在Laravel 4迁移中创建MYSQL过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以在Laravel 4迁移中生成存储的MYSQL过程?
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 Heredoc)
$query = <<<SQL
DELIMITER $$
DROP PROCEDURE IF EXISTS test$$
CREATE PROCEDURE test()
BEGIN
INSERT INTO `test_table`(`name`) VALUES('test');
END$$
DELIMITER ;
SQL;
DB:statement(DB::RAW($query));
在迁移的up()
函数中运行此命令时,出现此错误:
When Running this in a migration's up()
function I get this error:
推荐答案
您的代码有两个主要问题
There are two major problems with your code
-
DELIMITER
不是有效的sql语句.这只是一个MySql客户端命令.因此,请不要使用它. 顺便说一句,您得到的错误恰恰告诉了您. - 您不能使用
DB::statement
执行CREATE PROCEDURE
代码,因为它使用了已准备好的语句exec()
DB::connection()->getPdo()->exec()
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.- You can't use
DB::statement
to executeCREATE PROCEDURE
code because it uses prepared statement source code forConnection
. You can use PDOexec()
DB::connection()->getPdo()->exec()
instead
话虽如此,虚构的tags
表的样本迁移可能看起来像这样
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 = <<<SQL
DROP PROCEDURE IF EXISTS sp_insert_tag;
CREATE PROCEDURE sp_insert_tag(IN _name VARCHAR(32))
BEGIN
INSERT INTO `tags`(`name`) VALUES(_name);
END
SQL;
DB::connection()->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');
}
}
这篇关于在Laravel 4迁移中创建MYSQL过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文