可以使用Adonis的query builder来实现这个功能。以下是一个示例代码:
const Post = use('App/Models/Post')
const post = await Post.query()
.where('status', 'published')
.with('comments', (builder) => {
builder.where('approved', true)
})
.fetch()
const comments = post.toJSON().map(({ comments }) => comments)
console.log(comments)
这个示例代码使用了where方法来筛选status为"published"的posts,并使用with方法来获取这些posts的评论。通过给with方法传递一个回调函数,我们可以进一步筛选这些评论并只返回已经批准的评论。最后,使用toJSON方法将结果转换为JSON格式,然后使用map方法来返回每篇文章的评论。
如果我们只想返回使用where方法的结果,我们可以使用pluck方法来获取需要的数据:
const postIds = await Post.query()
.where('status', 'published')
.pluck('id')
console.log(postIds)
这个示例代码使用pluck方法来获取status为"published"的posts的ID。注意,pluck方法返回的是一个数组,其中只包含单个属性。所以我们只获取了文章的ID。