How to create triggers in Codeigniter's migrat

2019-07-07 16:53发布

问题:

Triggers creation are just not working, I tried everything I can think of, for instance, like that:

$this->db->query("DELIMITER //\r\n
CREATE TRIGGER `delete_post` BEFORE DELETE ON `posts`\r\n
FOR EACH ROW BEGIN\r\n
DELETE FROM page_content WHERE page_content.post_id = OLD.post_id;\r\n
END\r\n
//\r\n
DELIMITER ;");

And whatever I do, I have the feeling it won't create the trigger because Codeigniter create the SQL statement in only one line. Tried with and without the line breaks, still get this message:

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL     server version for the right syntax to use near 'DELIMITER // CREATE TRIGGER `delete_post` BEFORE DELETE ON `posts` FOR EAC' at line 1

DELIMITER // CREATE TRIGGER `delete_post` BEFORE DELETE ON `posts` FOR EACH ROW BEGIN DELETE FROM page_content WHERE page_content.post_id = OLD.post_id; END // DELIMITER ;

In PHPMyAdmin, the trigger create works by the way, so the SQL is valid

回答1:

You should remove the delimiter from the trigger while executing via PHP. mysql_ or mysqli_ functions should be able to execute the trigger without the delimiter.

Here is how to do it.

$this->db->query("
CREATE TRIGGER `delete_post` BEFORE DELETE ON `posts`\r\n
FOR EACH ROW BEGIN\r\n
DELETE FROM page_content WHERE page_content.post_id = OLD.post_id;\r\n
END\r\n
//\r\n
");