这是我的代码:
var query = Post.query(on: req.db)
if needFilter == true {
query = query.filter(\.$board.$id == boardId)
}
return try await query
.with(\.$profile).all()
上面的代码有点复杂。有没有办法这样写❓:
return try await query
.filter(\.$board.$id == boardId, enable: needFilter)
.with(\.$profile).all()
“启用:”表示此过滤器打开/关闭。
或者还有其他方法吗?有什么方便的方法吗?
提前致谢。
你可以这样实现:
return try await query
.filter { needFilter ? $0.$board.$id == boardId : true }
.with(\.$profile)
.all()