objection.js icon indicating copy to clipboard operation
objection.js copied to clipboard

this is question "how to?", not issues

Open deni5n opened this issue 4 years ago • 4 comments

Hello everyone. I did not find answers to my questions in the documentation and decided to ask them here.

Here is an example code:

async function(search){
  return Article.query()
      .select(
        '1.text as text_1',
        '0.text as text_2',
      )
      .from(
        [
        'article',
        Article.query()
          .select('article.article_id', 'article.text')
          .where(
            raw('LOWER(article.text)'),
            '=',
            raw(`ANY (LOWER(ARRAY ['${search}']::text)::text[])`)
          )
          .andWhere(raw('article.language_id = 2')),
        ]
      )
      .where(raw('"0".id in ("1".article_id)'))
}

Question_1: How to set the "main" alias for the article table? And alias "second", for the subquery. I tried .alias('main'), .as('main') and couldn't get it to work.

Question_2: How to get rid of raw queries ".andWhere(raw('article.language_id = 2'))". I was expecting this syntax ".andWhere('article.language_id', '=', '2')", but it doesn't work. Similarly with this query ".where(raw('"0".id in ("1".article_id)'))", expected this syntax ".where('"0".id', 'in', '" 1".article_id')", but it doesn't work.

Thanks in advance for your replies. You did a great job with objection.js

deni5n avatar Jan 31 '22 19:01 deni5n

Can you elaborate on what you're trying to do? Would also be helpful to know what your schema is and how your Model is defined.

caschbre avatar Feb 18 '22 21:02 caschbre

schema is defined like this

create table articles
(
     id serial not null primary key,
     texttext,
     language_id bigint
     article_id bigint
);

the articles table stores words and their translations, like so:

id | text | language_id | article_id
1  | milk | 1           | 2
2  | lait | 2           | one

query, searches for all words. for example for the word "milk":

text_1 | text_2
milk   | lait 

deni5n avatar Feb 22 '22 06:02 deni5n

@deni5n Can you also post your Models?

I've had similar situations where a table has a column that self-references, typically in a parent / child or hierarchical sense. I have a single Model for that table and then a relationship setup that defines the article_id -> id relation.

Then when you query articles, you can utilize that relation.

Article.query()
  .select('text')
  .withGraphFetched('myRelatedArticles')
  .modifyGraph('myRelatedArticles', qb => qb.select('text'))

That's not exact, nor tested, but that's generally how you can utilize your Model to query related data, even when it's relating to itself.

caschbre avatar Feb 24 '22 15:02 caschbre

Closing this in the absence of a response.

lehni avatar Apr 14 '23 23:04 lehni