所以我有一个posts表和一个types表。每个帖子都可以有多种类型。我已经在post模型中创建了一个HasManyRelation关系。不,我希望得到所有的帖子,这些帖子的type_id可能是1或2。这就是我尝试过的
const posts = await UserPost.query()
.select("id", "description", "price", "created_at")
.eager("[user, category, images, types]")
.modifyEager("types", builder => {
builder.where("user_post_type.type_id", 1)
})
.limit(limit)
.orderBy("created_at", "desc");这不管用。这只会过滤类型本身。但实际上并不返回具有该类型的帖子。我该怎么做呢?
发布于 2020-03-11 05:29:07
eager在查询之前获取帖子,在查询之后,您在.eager()的参数中写入每个eager。如果要按类型过滤帖子,则必须联接这些表,并使用.where()添加一个条件。这是脑海中浮现的第一个例子:
const posts = await UserPost.query()
.select("id", "description", "price", "created_at")
.leftJoin('types')
.eager("[user, category, images]")
.where('types.type_id', 1) // Condition
.limit(limit)
.orderBy("created_at", "desc");如果你想看其他的例子,这是link for documentation
https://stackoverflow.com/questions/59830227
复制相似问题