php – Laravel,从Migration创建MySQL触发器

我已经从迁移创建了MySQL存储过程,它工作得很好.

DB::unprepared('
    CREATE PROCEDURE sp_Create_Default_Task_1(IN _kid_id INT)
    BEGIN
        INSERT INTO tasks (kid_id, name) VALUES (_kid_id, \'daily\');
    END'
    );

此后我尝试使用以下代码创建MySQL触发器

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTrigger extends Migration {

    public function up()
    {
        DB::unprepared('
        CREATE TRIGGER tr_Task_Default AFTER INSERT ON `kids` FOR EACH ROW
            INSERT INTO tasks (`kid_id`, `name`) VALUES (NEW.id, \'Default\');
        ');
    }


    public function down()
    {
        DB::unprepared('DROP TRIGGER `tr_User_Default_Member_Role`');
    }
}

但是在我运行php artisan migrate之后它返回错误

{"error":{"type":
"Symfony\\Component\\Debug\\Exception\\FatalErrorException",
"message":"Class 'CreateTriggers' not found",
"file":"C:\\xampp\\htdocs\\dev03\\vendor\\laravel\\framework
\\src\\Illuminate\\Database\\Migrations\\Migrator.php",
"line":301}}

问题:出了什么问题?

解决方法:

类命名存在问题.

正确的类名可以帮助或像我一样,在记事本/文本中临时复制您的工作触发器代码.删除旧的迁移触发器文件并生成新的.

Note: By the way the same solution is valid for Laravel 4.x and Laravel 5.x

在Laravel 4

php artisan migrate:make create_trigger

在Laravel 5

php artisan make:migration create_trigger

生成后,我从我的记事本/文本中复制并粘贴相同的触发器代码,它工作得很好.

以下是通过迁移创建触发器的最终工作代码.

它适用于RAW和UNPREPARED方法.

<?php

use Illuminate\Database\Migrations\Migration;

class CreateTrigger extends Migration {

    public function up()
    {
        DB::unprepared('
        CREATE TRIGGER tr_User_Default_Member_Role AFTER INSERT ON `users` FOR EACH ROW
            BEGIN
                INSERT INTO role_user (`role_id`, `user_id`, `created_at`, `updated_at`) 
                VALUES (3, NEW.id, now(), null);
            END
        ');
    }

    public function down()
    {
        DB::unprepared('DROP TRIGGER `tr_User_Default_Member_Role`');
    }
}

Note: This is just example to demonstrate the concept

上一篇:MySQL事务和触发器


下一篇:mysql jdbc驱动程序不支持具有多个语句的触发器中的分隔符