这种关系是 OneToMany 还是 ManyToMany?
Is this relationship OneToMany or ManyToMany?
我有两个 tables ARTICLE
和 FAQ
(常见问题)。我试图在这两个 table 之间建立关系,但我很困惑!
我要实现的是文章可以有很多FAQ。因此,为此我应该创建一个枢轴 table 还是仅在 FAQ table?
中引用 FK
我试过但不确定下面的流程是否正确?
文章table:
CREATE TABLE IF NOT EXISTS `article` (
`id` int(11) UNSIGNED NOT NULL,
`title` varchar(255) DEFAULT NULL,
`slug` varchar(255) DEFAULT NULL,
`description` longtext NOT NULL,
PRIMARY KEY (`id`)
);
常见问题解答 Table 架构:
CREATE TABLE IF NOT EXISTS `eb_faq` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`faq_category_id` bigint(20) UNSIGNED DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`question` text NOT NULL,
`answer` text NOT NULL,
PRIMARY KEY (`id`)
);
枢轴:
CREATE TABLE IF NOT EXISTS `article_linked_faq` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`article_id` int(11) DEFAULT NULL,
`faq_id` int(11) DEFAULT NULL,
`order_by` int(11) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
这个架构确实允许一篇文章有多个常见问题解答,但也允许一个常见问题解答链接到多篇文章。如果那是你想要的,太好了!如果不是那么我建议删除枢轴 table 并将 article_id 添加到 eb_faq.
不,您只需要在 faq table 中添加外键,它将创建两个 table 之间的关系。无需创建第三个 table
CREATE TABLE IF NOT EXISTS `eb_faq` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`articleId` int(11),
`faq_category_id` bigint(20) UNSIGNED DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`question` text NOT NULL,
`answer` text NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (articleId) REFERENCES article(id)
);
我有两个 tables ARTICLE
和 FAQ
(常见问题)。我试图在这两个 table 之间建立关系,但我很困惑!
我要实现的是文章可以有很多FAQ。因此,为此我应该创建一个枢轴 table 还是仅在 FAQ table?
中引用FK
我试过但不确定下面的流程是否正确?
文章table:
CREATE TABLE IF NOT EXISTS `article` (
`id` int(11) UNSIGNED NOT NULL,
`title` varchar(255) DEFAULT NULL,
`slug` varchar(255) DEFAULT NULL,
`description` longtext NOT NULL,
PRIMARY KEY (`id`)
);
常见问题解答 Table 架构:
CREATE TABLE IF NOT EXISTS `eb_faq` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`faq_category_id` bigint(20) UNSIGNED DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`question` text NOT NULL,
`answer` text NOT NULL,
PRIMARY KEY (`id`)
);
枢轴:
CREATE TABLE IF NOT EXISTS `article_linked_faq` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`article_id` int(11) DEFAULT NULL,
`faq_id` int(11) DEFAULT NULL,
`order_by` int(11) DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
);
这个架构确实允许一篇文章有多个常见问题解答,但也允许一个常见问题解答链接到多篇文章。如果那是你想要的,太好了!如果不是那么我建议删除枢轴 table 并将 article_id 添加到 eb_faq.
不,您只需要在 faq table 中添加外键,它将创建两个 table 之间的关系。无需创建第三个 table
CREATE TABLE IF NOT EXISTS `eb_faq` (
`id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
`articleId` int(11),
`faq_category_id` bigint(20) UNSIGNED DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`question` text NOT NULL,
`answer` text NOT NULL,
PRIMARY KEY (`id`),
FOREIGN KEY (articleId) REFERENCES article(id)
);