Mysql trigger to update the inserted row

孤街醉人 提交于 2019-12-13 19:03:17

问题


I'm facing a problem: I want to update a record that being inserted to a table with trigger:

DELIMITER $$
CREATE TRIGGER moodle.update_lang
AFTER INSERT
ON moodle.mdl_user FOR EACH ROW
BEGIN
   update moodle.mdl_user SET lang='hu' WHERE lang='en';
END$$
DELIMITER ;

So when I want to insert a row now, it gives me an error that the row can't be inserted because a procedure is already using it. Can you give any solutions how to make this work? Is this method usable or should I aproach the problem from a different angle? Thanks in advance!


回答1:


As per comments :)

You require a BEFORE INSERT trigger. In that trigger, you alter the record before it reaches permanent storage. Using your example, this trigger would be defined like this:

DELIMITER $$
CREATE TRIGGER moodle.update_lang
BEFORE INSERT
ON moodle.mdl_user FOR EACH ROW
BEGIN
   SET NEW.lang='hu';
END$$
DELIMITER ;

The reason you can't use UPDATE on the same table that trigger refers to is because that could (and would) cause an infinite loop.

Note: I haven't tested this, but judging by your comments it seems to be working. Good luck!




回答2:


I wouldn't recommend using database triggers because Moodle can use several databases. You might need to transfer to another database in the future.

You can set the default language in site admin -> language -> language settings -> default language. Or direct to /admin/settings.php?section=langsettings

Or add this to config.php

$CFG->lang = 'hu';

Or respond to the user_created event and update the record

https://docs.moodle.org/dev/Events_API#Handling_an_event

Create a local plugin

https://docs.moodle.org/dev/Local_plugins

Then add the following code:

In local/yourplugin/db/events.php

$handlers = array (
    'user_created' => array (
        'handlerfile'      => '/local/yourplugin/locallib.php',
        'handlerfunction'  => 'local_yourplugin_user_created',
        'schedule'         => 'instant',
        'internal'         => 1,
    ),
);

Then in /local/yourplugin/locallib.php

function local_yourplugin_user_created($eventdata) {
    global $DB;

    $userid = $eventdata->objectid;

    $DB->set_field('user', 'lang', 'hu', array('id' => $userid);

    return true;
}


来源:https://stackoverflow.com/questions/33628112/mysql-trigger-to-update-the-inserted-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!