go to index

Strapi实现根据slug查找记录

read time 2 min read
Strapi slug api

简介

Strapi 默认情况下是通过 id 来查找单条记录的。在博客系统中,我们通常需要通过 slug 字段进行查询。本文以 Posts 为例,介绍如何实现根据 slug 查找记录。

假设你已经在数据模型中添加了 slug 字段,本文将不再赘述其创建过程。

步骤

第一步:定义路由

在源码目录 src/api/post/routes 下新建一个 _custom.js 文件,定义新的路由:

javascript
module.exports = {
  routes: [
    {
      method: 'GET',
      path: '/posts/:slug',
      handler: 'post.findOne',
      config: {
        auth: false, // 根据需求配置认证
      },
    }
  ]
};

第二步:实现控制器方法

修改源码目录 src/api/post/controllers 下的 post.js 文件,添加 findOne 方法:

javascript
'use strict';

/**
 * post controller
 */

const { createCoreController } = require('@strapi/strapi').factories;

module.exports = createCoreController('api::post.post', ({ strapi }) => ({
  async findOne(ctx) {
    const { slug } = ctx.params;
    const { query } = ctx;

    try {
      const entity = await strapi.db.query('api::post.post').findOne({
        where: { slug },
        populate: query.populate ? query.populate.split(',') : [], // 根据需要处理关联字段
      });

      if (!entity) {
        return ctx.notFound('Post not found');
      }

      const sanitizedEntity = await this.sanitizeOutput(entity);

      return this.transformResponse(sanitizedEntity);
    } catch (error) {
      return ctx.badRequest(null, [{ messages: [{ id: error.message }] }]);
    }
  },
}));

测试

重启 Strapi 控制台后,请求 /api/posts/文章id 将会返回 404,而请求 /api/posts/文章slug 将会返回对应的记录。