【问题标题】:Bookshelf.js withRelated TypeScript errorBookshelf.js 与相关的 TypeScript 错误
【发布时间】:2020-12-31 05:01:12
【问题描述】:

因此,在我的应用中,我有相互关联的类别文章。一开始我检索了所有的categories,每个里面都有articles。问题是我想通过userId 过滤其中的 categoriesarticles 但我不知道该怎么做,因为我正在使用 TypeScript 并出现错误。

const articlesInCategories = (await (await ArticleCategory.fetchAll())
    .query((qb: QueryBuilder) => {
        qb.innerJoin(Table.ARTICLE_CATEGORY_RELATION, 'article_category_relation.category_id', 'article_category.id' );
        qb.innerJoin(Table.ARTICLE, 'article.id', 'article_category_relation.article_id');

        // Next condition is only for Categories not for Articles inside it
        if (roleId == Role.manager) {
            qb.where('user_id', userId);
        }

        qb.orderBy('id', 'desc');
      })
      .fetch({
          withRelated: [{'articles': function (qb: QueryBuilder) => qb.where('user_id', userId)}]
      }));

如果userId 例如是1,则只想获取那些类别,其中包含由ID为1的用户撰写的文章。此外,并非所有文章,而是仅由 ID 为 1 的用户撰写。

withRelated 附近有 TS 错误:Type '{ articles: (qb: QueryBuilder) => QueryBuilder<any, any[]>; }' is not assignable to type 'string'.ts(2322)

在这种情况下你能帮我用 TypeScript 吗?或者建议任何替代方法来实现我想要的?

【问题讨论】:

    标签: node.js typescript orm knex.js bookshelf.js


    【解决方案1】:

    嗯,那是错误的方法。如果我执行以下操作,效果会非常好:

    const articlesInCategories = await new ArticleCategory().query((qb: QueryBuilder) => {
        .query((qb: QueryBuilder) => {
            qb.innerJoin(Table.ARTICLE_CATEGORY_RELATION, 'article_category_relation.category_id', 'article_category.id' );
            qb.innerJoin(Table.ARTICLE, 'article.id', 'article_category_relation.article_id');
    
            if (roleId == Role.manager) {
                qb.where('user_id', userId);
            }
    
            qb.orderBy('id', 'desc');
          })
          .fetch({
              withRelated: [{ 'articles': (qb: QueryBuilder) => qb.where('user_id', userId) }]
          }));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      • 2016-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多