dongqian1028 2014-12-10 21:13
浏览 190
已采纳

Laravel,从Migration创建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'
    );

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`');
    }
}

But it returns error after I run 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}}

Question: What is going wrong?

  • 写回答

3条回答 默认 最新

  • dow58115 2014-12-11 08:51
    关注

    There was issue with class naming.

    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.

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

    In Laravel 4

    php artisan migrate:make create_trigger
    

    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.

    it works both with RAW and UNPREPARED method.

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办