简体   繁体   English

如何使用触发器(MySQL)在插入时更改同一表的字段值

[英]How to change a field value of the same table on insert using trigger (MySQL)

I have an 'example_table' and it has several fields.我有一个“example_table”,它有几个字段。 I want to change the 'example_field' value on insert into this same table when example_field='Faiyaj' AND example_field_two Like '096%' then i want to set the example_field = 'Faiyaj11'.当 example_field='Faiyaj' AND example_field_two Like '096%' 然后我想设置 example_field = 'Faiyaj11' 时,我想更改插入到同一个表中的 'example_field' 值。

Here is my migration table (UP function):这是我的迁移表(UP 函数):

public function up()
{
   $this->create('example_table', function (Blueprint $table) {

       $table->bigIncrements('id');
       $table->integer('user_id')->unsigned();
       $table->text(description, 1600);
       $table->string('example_field');
       $table->string('example_field_two');
       $table->timestamp('created_at');

   });


   $insertTrigger = "CREATE TRIGGER example_table_generator_insert AFTER INSERT ON example_table
FOR EACH ROW
BEGIN
IF EXISTS(SELECT * FROM example_table WHERE example_field='Faiyaj' AND example_field_two Like '096%') THEN
UPDATE `example_table` SET `example_field` = 'Faiyaj11';
END IF;
END;
";


   $this->unprepared($insertTrigger);

}

I have used the above trigger in my migration table but it's not working and it is not inserting any value in the database.我在迁移表中使用了上述触发器,但它不起作用,也没有在数据库中插入任何值。 I have tried the trigger in several ways but failed.我曾以多种方式尝试过触发器,但都失败了。 (BEFORE/AFTER INSERT) (插入前/插入后)

I have solved the problem today.我今天已经解决了这个问题。 Here is the solution :这是解决方案:

$insertTrigger = "CREATE TRIGGER example_table_generator_insert BEFORE INSERT ON example_table
FOR EACH ROW IF NEW.example_field = 'Faiyaj' AND NEW.example_field_two LIKE '096%' THEN SET NEW.example_field = 'Faiyaj11';
END IF;";

$this->unprepared($insertTrigger);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM