node.js - How can I select specific columns from a joined table in Knex.js? -
i have worked 20 years sql databases , seem have trouble understanding knex way map queries. can me correct code?
i have sql query want use in nodejs application:
select p.id, p.project_number, p.project_name, p.start_date, p.end_date, o.name, o.email_addr, c.company, c.email_addr company_email, c.first_name, c.last_name projects p inner join owners o on o.id = p.owner_id inner join clients c on c.id = p.client_id
knexjs (0.7.5) documentation shows example query:
knex.from('projects').innerjoin('owners', 'owners.id', 'projects.owner_id') .innerjoin('clients', 'clients.id', 'projects.client_id');
there couple of things cannot find in documentation:
1) how select columns want include? projects, clients , owners each have 20 50 columns , not interested in of them. selecting columns main table clear (using select() or column() ) how select columns joined tables?
2) columns have identical names. how can avoid name conflicts (i.e. add prefix columns other tables)? looked @ way knex can generate column aliases (... ...) , not sure viable option more complex queries. (even relatively simple queries 1 above)
you can try:
knex('projects').select(['projects.id', 'projects.project_number', 'projects.project_name', 'projects.start_date', 'projects.end_date', 'owners.name', 'owners.email_addr owner_email_addr', 'clients.company', 'clients.email_addr client_email_addr', 'clients.first_name', 'clients.last_name']) .innerjoin('owners', 'owners.id', 'projects.owner_id') .innerjoin('clients', 'clients.id', 'projects.client_id');
hope helps!
Comments
Post a Comment