Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

node.js - Bookshelf.js withRelated TypeScript error

So, in my app I have categories and articles that are interrelated. At first I retrieve all of categories and there are articles inside each of them. The problem is I wanna filter both categories and articles inside it by userId but I don't know how to do it since I'm using TypeScript and getting error.

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)}]
      }));

If userId for example would be 1, wanna get only those categories which contain articles written by user with id 1. MOREOVER, not all articles, but ONLY written by user with id 1.

I have TS error near withRelated: Type '{ articles: (qb: QueryBuilder) => QueryBuilder<any, any[]>; }' is not assignable to type 'string'.ts(2322)

Can you help me please with TypeScript in such case or suggest any alternative ways to achieve what I want?

question from:https://stackoverflow.com/questions/65516828/bookshelf-js-withrelated-typescript-error

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, that was the wrong approach. If I do the following, it works brilliant:

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) }]
      }));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...