Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/250.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用一个项目保存多个类别_Php_Sql_Database Design - Fatal编程技术网

Php 使用一个项目保存多个类别

Php 使用一个项目保存多个类别,php,sql,database-design,Php,Sql,Database Design,我正在建立一个网站,您可以在其中添加多个类别的项目 在一个字段中存储多个类别并保持字段可搜索的最佳方式是什么?最好的方式是而不是在一个字段中存储多个类别 相反,为ItemCategories创建一个单独的表 阅读和内部摘要。您可以构建一个关系表,如项目类别,它只存储类别id和项目id。然后您可以直接将搜索查询放在关系表上。确保它也有自己的主键。您不应该尝试将所有类别存储在一个字段中,这就是“关系表”的用途,您应该像这样构建表: product_categories ( `id` INT

我正在建立一个网站,您可以在其中添加多个类别的项目


在一个字段中存储多个类别并保持字段可搜索的最佳方式是什么?

最好的方式是而不是在一个字段中存储多个类别

相反,为ItemCategories创建一个单独的表


阅读和内部摘要。

您可以构建一个关系表,如
项目类别
,它只存储类别id和项目id。然后您可以直接将搜索查询放在关系表上。确保它也有自己的主键。

您不应该尝试将所有类别存储在一个字段中,这就是“关系表”的用途,您应该像这样构建表:

product_categories (
    `id` INT AUTO_INCREMENT,
    `product_id` INT NOT NULL,
    `category_id` INT NOT NULL,
    PRIMARY KEY (`id`),
    UNIQUE KEY (`product_id`, `category_id`)
)

通过这种方式,您还可以添加将负责更改、删除等的内容。

如果不在一个字段中存储多个类别,您可以创建一个单独的表来为每个项目分配类别。与此类似:

-- create your table to store items/products
create table items
(
  id int,  -- this will be the PK
  name varchar(10)
);

insert into items values
(1, 'product1'),
(2, 'product2');

-- create your table to store categories
create table categories
(
  id int,  -- this will be the PK
  name varchar(50)
);

insert into categories values
(1, 'color'),
(3, 'material'),
(6, 'size');

-- create your join table to assign the categories to each item
-- this table will have a foreign key relationship to the items and categories table
create table items_categories
(
  item_id int,   -- both fields will be the PK
  category_id int
);

insert into items_categories values
(1,  1),
(2,  3),
(2,  6);
然后,您将通过连接表来查询数据:

select i.id itemid,
  i.name item,
  c.name category
from items i
left join items_categories ic
  on i.id = ic.item_id
left join categories c
  on ic.category_id = c.id

请参见

在单个条目中存储单独的项目很少是个好主意


但是,如果您真的坚持这样做,那么最好的方法可能是序列化您可能已存储为数组的类别,例如使用
json\u serialize
。然后使用sqls
LIKE
操作符搜索数据库

最好的方法是为每个类别设置单独的字段,然后必须有一个表来存储项目和类别之间的引用。需要更多的解释