EAV(Entity–Attribute–Value,实体-属性-值)模型常用于结构灵活、字段不固定的业务场景,比如电商商品、CMS 内容、配置项等。用在内容聚合页上时,核心目标是:
用一套统一模型存储多种内容类型,再按条件聚合展示。
下面按“思路 → 表结构 → 查询 → 聚合页实现”逐步说明。
内容聚合页通常包含:
EAV 的优势:
value 取数据content (
id,
type, -- article / video / product
title,
created_at
)
attribute (
id,
name, -- author / duration / price / tag
type -- string / int / datetime
)
content_attribute (
content_id,
attribute_id,
value
)
文章
content: id=1, type=article, title="EAV 入门"
attribute: author, tag
content_attribute:
(1, author, "张三")
(1, tag, "数据库")
视频
content: id=2, type=video, title="EAV 实战"
attribute: duration, tag
content_attribute:
(2, duration, "10:23")
(2, tag, "数据库")
SELECT c.*
FROM content c
JOIN content_attribute ca
ON c.id = ca.content_id
WHERE ca.attribute_id = (SELECT id FROM attribute WHERE name='tag')
AND ca.value = '数据库'
ORDER BY c.created_at DESC;
WHERE c.type IN ('article','video')
AND ca.value = '数据库'
SELECT
c.id,
MAX(CASE WHEN a.name='author' THEN ca.value END) AS author,
MAX(CASE WHEN a.name='duration' THEN ca.value END) AS duration
FROM content c
JOIN content_attribute ca ON c.id = ca.content_id
JOIN attribute a ON ca.attribute_id = a.id
GROUP BY c.id;
type 渲染不同字段attribute如果你愿意,我可以:
你现在是哪种技术栈?
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。