Laravel,从迁移创建MySQL触发器 [英] Laravel, create MySQL trigger from Migration

查看:104
本文介绍了Laravel,从迁移创建MySQL触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从迁移中创建了MySQL存储过程,并且工作正常.

I have created MySQL stored procedure from migration and it works just fine.

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触发器

Hereafter I tried to do the same to create MySQL trigger with following code

<?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}}

问题:出了什么问题?

推荐答案

类命名存在问题.

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

Correct class name could help OR do as I did, Copy your working trigger code temporary in notepad/text. Delete the old migration trigger file and generate new one.

注意:顺便说一句,相同的解决方案对Laravel 4.x和Laravel 5.x有效.

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

在Laravel 4中

In Laravel 4

php artisan generate:migration create_trigger

在Laravel 5中

In Laravel 5

php artisan make:migration create_trigger

生成后,我从记事本/文本中复制并粘贴了相同的触发代码,效果很好.

After it was generated I copy and paste the same Trigger code from my notepad/text and it works just fine.

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

Here is the final working code for creating trigger through migration.

它同时适用于RAWUNPREPARED方法.

<?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

这篇关于Laravel,从迁移创建MySQL触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆