Strapi v4关联字段获取Image列报错:字段存在却提示无该列
问题场景
通过slug获取单个分类的接口地址为http://localhost:1337/api/categories/{slug},控制器代码如下:
async findOne(ctx) { const {id : slug} = ctx.params const response = await strapi.db .query("api::category.category") .findOne({ where: { slug: slug }, populate: { blogs: { select: ["id", "title"], orderBy: ["id"], }, }, });
仅选择id和title时查询正常,但添加image字段到select数组后:
select: ["id", "title", "image"],
出现错误:
error: select distinct
t1.blog_order,t0.id,t0.id,t0.title,t0.image,t1.category_idfromblogsast0
left joincategories_blogs_linksast1ont0.id=t1.blog_idwhere (t1.category_idin (2)) order byt0.id
asc,t1.blog_orderasc - no such column: t0.image SqliteError:
select distinctt1.blog_order,t0.id,t0.id,t0.title,t0.image,t1.category_idfromblogsast0left joincategories_blogs_linksast1ont0.id=t1.blog_idwhere
(t1.category_idin (2)) order byt0.idasc,t1.blog_order
asc - no such column: t0.image
Blog模型中确实存在image字段,但无法通过直接select获取。
问题原因
Strapi中的媒体字段(如image)并非直接存储在blogs表中,而是存储在独立的upload_file表中,与blogs表通过关联关系绑定。因此直接在select数组中添加image会导致SQL查询试图读取不存在的t0.image列,引发错误。
解决方案
需要在blogs的populate配置中嵌套image字段的获取规则,而非将其放入select数组。修改后的控制器代码如下:
async findOne(ctx) { const {id : slug} = ctx.params const response = await strapi.db .query("api::category.category") .findOne({ where: { slug: slug }, populate: { blogs: { select: ["id", "title"], // 仅选择blogs表的直接字段 orderBy: ["id"], populate: { // 嵌套populate媒体字段 image: { select: ["url", "name", "id"] // 按需选择image的字段 } } }, }, });
说明
- 媒体字段需要通过嵌套
populate来获取,因为它属于关联实体; - 可以在
image的select中指定需要返回的媒体字段(如url、name等),避免返回冗余数据; - 执行修改后的代码后,接口将正确返回包含
image信息的博客列表。
内容的提问来源于stack exchange,提问作者Sai Krishna

