如何为Laravel迁移创建没有条件且没有分隔符的MySQL触发器?

时间:2018-08-13 01:57:25

标签: php mysql laravel laravel-migrations

我有一个Laravel项目,该项目已经有一个带有SQL脚本的数据库,并且我试图将MySQL脚本放入迁移中,以改用Eloquent。我的数据库具有使用DELIMITER $$的触发器,并且根据此question,看来我不能在脚本中使用DELIMITER $$,因为它是MySQL客户端命令,而MySQL PDO没有使用PHP进行访问。

是否可以避免DELIMITER $$,但在MySQL触发器中仍然有条件,以使其可用于Laravel数据库迁移?

migration.php:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;

class RunInitScriptSql extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
     public function up()
     {
        $sql_dump = File::get(base_path("database/billing_system_stable.sql"));
        $sql_dump_insert = File::get(base_path("database/billing_system_insertions.sql"));
        $sql_dump_trigger = File::get(base_path("/database/billing_system_triggers.sql"));

        DB::connection('mysql')->getPdo()->exec("CREATE DATABASE IF NOT EXISTS billing_system;");
        DB::connection('mysql')->getPdo()->exec(
            $sql_dump .
            $sql_dump_insert .
            $sql_dump_trigger
        );
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {

    }
}

示例触发器:

DROP TRIGGER IF EXISTS before_update_typesoumission;
DELIMITER $$
CREATE TRIGGER before_update_typesoumission
  BEFORE UPDATE
  ON typesoumission
  FOR EACH ROW
    IF NEW.typeSoumission = 'Résidentiel'
    THEN
      SET NEW.ratio = 1;
    ELSE
      SET NEW.ratio =
      NEW.tauxHoraire / (SELECT tauxHoraire
                         FROM typesoumission
                         WHERE typeSoumission = 'Résidentiel');
    END IF;
$$
DELIMITER ;

1 个答案:

答案 0 :(得分:1)

注意尽管此解决方案在MySQL上运行良好,但OP正在使用似乎不喜欢的MariaDB。

您应该能够只将 return ( <li className={completeClass} onClick={() => this.handleTodoClick(todo)}> {todo.description} <button onClick= {(todo)=>this.handleTodoDelete(todo)}>delete</button> </li> 放入查询中。就我而言,我使用CREATE TRIGGER(来自$link的结果)作为连接。我正在运行PHP7和MySQL5.6:

$link = new PDO("mysql:host=$server;dbname=$db;charset=utf8", $user, $pass, $options);

输出:

$link->exec("DROP TRIGGER IF EXISTS before_update_typesoumission");
$link->exec("CREATE TRIGGER before_update_typesoumission
  BEFORE UPDATE
  ON typesoumission
  FOR EACH ROW
    IF NEW.typeSoumission = 'Résidentiel'
    THEN
      SET NEW.ratio = 1;
    ELSE
      SET NEW.ratio =
      NEW.tauxHoraire / (SELECT tauxHoraire
                         FROM typesoumission
                         WHERE typeSoumission = 'Résidentiel');
    END IF;");
$result = $link->query("SELECT * FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_NAME='before_update_typesoumission'");
print_r($result->fetch());