Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

php - Laravel, create MySQL trigger from Migration

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 IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 generate:migration 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 IlluminateDatabaseMigrationsMigration;

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...