You can implement a trigger AFTER INSERT
in Usuarios
. The idea is to use the command INSERT ... SELECT
to select all the challenges and insert corresponding entries in Usuarios_tem_desafios
:
DELIMITER //
CREATE TRIGGER novos_desafios AFTER INSERT ON Usuarios
FOR EACH ROW
BEGIN
INSERT INTO Usuarios_tem_desafios
(id_usuario, id_desafio, status)
SELECT NEW.id, id, 'novo'
FROM Desafios;
END;//
DELIMITER ;
See working at Paiza.io
That said, while the OP made it clear in the comments that this is an academic project, I advise avoiding the most of dealing with business rules in triggers . This small example is certainly dealing with business rules:
When inserting a user it must be associated with new challenges.
A challenge associated with a user should start with the "new" status (my kick)
The problem is that in real software business rules can evolve over time, because of this, it's always a good idea to keep the code centralized in an easy-to-maintain layer. Triggers are the opposite of that, the code spreads and maintenance can quickly become a headache.
There is nothing wrong with using triggers to handle Cross-cutting concerns , for example to maintain audit records, etc. But my recommendation is to always try to minimize the use of triggers .