P
P
Polina Titova2021-09-05 18:13:42
MySQL
Polina Titova, 2021-09-05 18:13:42

How to write relationships in a database schema?

When creating one table, it refers to external values ​​from another table, that is, a many-to-many relationship is implemented using the example of users and reviews:

spoiler
CREATE TABLE IF NOT EXISTS `task_force`.`users` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `reviews` INT UNSIGNED NOT NULL,

    FOREIGN KEY (`reviews`) REFERENCES `reviews` (`id`),
    PRIMARY KEY (`id`)
);

CREATE TABLE IF NOT EXISTS `task_force`.`reviews` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `user_id` INT UNSIGNED NOT NULL,

    FOREIGN KEY (`user_id`) REFERENCES `users` (`id`),
    PRIMARY KEY (`id`)
);

The first table is not created, since it cannot take a value from a table that does not yet exist, because it is located below:
spoiler
6134dba53a056294025342.png

How can you describe the circuit without these errors? To create at first tables, and then to register communications, as separate request? And is there a compact solution in one file without migrations?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mletov, 2021-09-05
@poly-titova

If many to many, then there must also be a link table usersToReviews.
But in general this is very strange.... 10 users collectively wrote 1 review... Seriously?) If
it's still one to many, which I suspect you meant, then:
users? It's not needed, remove it.
- How to delete, the problem will be solved by itself: first create users, and only then reviews with a link to users

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question