如何从 Contentful 获取单个条目并按字段值查询? [英] How to fetch a single entry from Contentful and query by field value?

查看:21
本文介绍了如何从 Contentful 获取单个条目并按字段值查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据条目的名称自定义字段检索单个条目.

I am trying to retrieve a single entry based on the name custom field of my entry.

我尝试过使用 JS SDK 和各种选项:

I have tried using the JS SDK with various options:

client.getEntry("entryID")
    // .where("content_type", "Restaurant")
    // .where("fields.name[match]", "RestaurantName")
    // .all()
    .then(data => console.log('data', data))
    .catch(err => console.log('err', err))

但根据返回的错误,建议我只能使用 .getEntry 并传入条目 ID.

But based on the errors back, it's suggesting I can only use .getEntry and pass in the entry ID.

我还考虑过使用 axios 发出 HTTP 请求,但遇到了类似的问题,即只能检索条目的完整列表或根据条目 ID 进行过滤.

I also looked at making an HTTP request with axios but faced a similar issue with only being able to retrieve either a full list of entries or filtered based on the entry ID.

有没有我可以通过`field.name ===Slug"或我添加的其他自定义字段获取的东西?

Is there a away I can fetch by `field.name === "Slug" or some other custom field I have added?

推荐答案

目前使用 getEntry 获取条目的唯一方法是传入 sys.id 值.我们在任何时候向 Contentful 请求任何内容时都使用单个控制器.这允许我们设置错误消息,将返回的数据转换为我们想要的格式等.我们向控制器添加了我们自己的 getEntry 辅助函数,可以通过

Currently the only way to get an entry using getEntry, is to pass in the sys.id value. We use a single controller anytime that we request anything from Contentful. This allows us to set error messages, transform the data returned into the format we want etc. We added to the controller our own getEntry helper function that can be called by

contentfulController.getEntries({
   content_type: 'indexPage',
   'fields.slug[match]': slug,
   include: 3,
   locale: language,
});

然后在我们自己的 getEntry 函数中,我们获取数组中的第一个,并返回对象,因为我们总是知道我们将返回一个.

Then inside our own getEntry function we grab the first one in the array, and return the object since we always know we will be returning one.

但是,请务必注意,如果 slug 中有子字符串,这可能会导致问题.假设您有两个带有 slug 的物品:

However its important to note that this can cause issues if you have sub strings in the slug. Lets say you have two items with the slugs:

/resource
/resourcelisting

如果您查询 'fields.slug[match]': '/resource',它将在结果中返回这两项,因此您还应该检查哪一项具有您想要的实际 slug,而不是其中的一部分.

If you query 'fields.slug[match]': '/resource', it will return both items in the results so you should also check which one has the actual slug you want, not part of it.

这篇关于如何从 Contentful 获取单个条目并按字段值查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆