【问题标题】:Fetch posts by types in Objection.js?在 Objection.js 中按类型获取帖子?
【发布时间】:2020-05-06 20:56:06
【问题描述】:

所以我有一个帖子表和一个类型表。每个帖子可以有多种类型。我在 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");

这不起作用。这只是过滤类型本身。但实际上并没有返回该类型的帖子。我该怎么做?

【问题讨论】:

    标签: mysql node.js knex.js objection.js


    【解决方案1】:

    eager 在查询之前获取 Post 并在查询之后为您在 .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

    【讨论】:

      猜你喜欢
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 2012-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多