如何从 Strapi 内容 API 获取随机记录

Par*_*ban 8 strapi

我在 Strapi 有记录。我正在使用 Strapi 内容 API。在我的前端,我只需要随机显示 2 条记录。为了进行限制,我使用了内容 API 的限制查询。但随机获取我需要使用的关键字。官方文档没有提供有关此的任何详细信息 - https://strapi.io/documentation/v3.x/content-api/parameters.html#available-operators

Mar*_*ack 5

没有随机的官方 Strapi API 参数。你必须实施你自己的。以下是我之前使用 Strapi v3 所做的操作:

1 - 制作服务功能

文件:api/mymodel/services/mymodel.js

这将包含我们实际的随机查询 (SQL),并将其包装在服务中很方便,因为它可以在很多地方使用(cron 作业、其他模型内等)。

module.exports = {
    serviceGetRandom() {

        return new Promise( (resolve, reject) => {
            
            // There's a few ways to query data.
            // This example uses Knex.
            const knex = strapi.connections.default
            let query = knex('mydatatable')

            // Add more .select()'s if you want other fields
            query.select('id')

            // These rules enable us to get one random post
            query.orderByRaw('RAND()')
            query.limit(1)

            // Initiate the query and do stuff
            query
            .then(record => {
                console.log("getRandom() record: %O", record[0])
                resolve(record[0])
            })
            .catch(error => {
                reject(error)
            })
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

2 - 在某个地方使用该服务,例如控制器:

文件:api/mymodel/controllers/mymodel.js

module.exports = {

    //(untested)

    getRandom: async (ctx) => {

        await strapi.services.mymodel.serviceGetRandom()
        .then(output => {
            console.log("getRandom output is %O", output.id)
            ctx.send({
                randomPost: output
            }, 200)
        })
        .catch( () => {
            ctx.send({
                message: 'Oops! Some error message'
            }, 204) // Place a proper error code here
        })

    }

}
Run Code Online (Sandbox Code Playgroud)

3 - 创建指向该控制器的路由

文件:api/mymodel/config/routes.json

...
    {
        "method": "GET",
        "path": "/mymodelrandom",
        "handler": "mymodel.getRandom",
        "config": {
            "policies": []
        }
    },
...
Run Code Online (Sandbox Code Playgroud)

4 - 在您的前端中,访问路线

(无论您如何访问 API)

例如ajax调用/api/mymodelrandom