question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

fetchAll, and select specific column from related

See original GitHub issue

Hi all, I’ve an issue I can’t understand.

I have two models :

file.js

const bookshelf = require('../database');

require('./moderation');

const File = bookshelf.Model.extend({
  tableName: 'file',
  moderation() {
    return this.hasMany('Moderation', 'file');
  }
});

module.exports = bookshelf.model('File', File);

moderation.js

const bookshelf = require('../database');

const Moderation = bookshelf.Model.extend({
  tableName: 'moderation',
  file() {
    return this.belongsTo('File', 'file');
  }
});
module.exports = bookshelf.model('Moderation', Moderation);

And I aim to do something like this :

File
    .where('user', userId)
    .fetchAll({
      withRelated: [{
        moderation(query) {
          query.select('comment', 'created_at'); // <--- doesn't work
          query.orderBy('created_at', 'DESC'); // <--- works if previous line is commented
        }
      }],
      debug: true,
    })
    .then((files) => {
      console.log(JSON.stringify(files.toJSON(), null, 4));
    })
    .catch((err) => {
      console.log('err', err);
    });

If I add a query.select in the withRelated, I simply get an empty array, but if I add a query.orderBy('created_at', 'DESC'), and only it, it works (list my ‘moderations’ in the returned object, sort by creation date desc)

Do I do something wrong ?

The logs :

with the select and order by:

{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ '1409508080453948467' ],
  __knexQueryUid: 'a0000a2b-4dc4-4c76-873f-384bf3e133f5',
  sql: 'select "file".* from "file" where "user" = ?' }
{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ '1424566923860907012', '1414402803459168246' ],
  __knexQueryUid: '69e422a7-869e-44b1-9963-279e6ed861a8',
  sql: 'select "comment", "created_at" from "moderation" where "moderation"."file" in (?, ?) order by "created_at" DESC' }

without the select :

{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ '1409508080453948467' ],
  __knexQueryUid: 'b223bc7e-4684-41e8-b33d-f1135e969c7c',
  sql: 'select "file".* from "file" where "user" = ?' }
{ method: 'select',
  options: {},
  timeout: false,
  cancelOnTimeout: false,
  bindings: [ '1424566923860907012', '1414402803459168246' ],
  __knexQueryUid: '44bfd21e-fc33-4c32-8ca2-1cdf1230094a',
  sql: 'select "moderation".* from "moderation" where "moderation"."file" in (?, ?) order by "created_at" DESC' }

Edit: While digging into this issue, I’ve tried to change the model :

file.js

const bookshelf = require('../database');

require('./moderation');

const File = bookshelf.Model.extend({
  tableName: 'file',
  hasTimestamps: ['created_at', 'updated_at'],
  moderation() {
    return this.hasMany('Moderation', 'file')
      .query({
        select: ['moderation.comment', 'moderation.created_at'],
        orderBy: ['moderation.created_at', 'DESC']
      });
  }
});

module.exports = bookshelf.model('File', File);

And then

File
    .where('user', userId)
    .fetchAll({
      withRelated: ['moderation'],
      debug: true,
    })
    .then((files) => {
      console.log(JSON.stringify(files.toJSON(), null, 4));
    })
    .catch((err) => {
      console.log('err', err);
    });

but same issue

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:10

github_iconTop GitHub Comments

1reaction
oscarooxcommented, Jan 17, 2017

@kai23 after looking at your models i’ve noticed that a File can have many moderations, meaning that you would have to select the foreign key of the file with the comment and created_at. It should work if you also select the foreign key

query.select('comment', 'created_at', 'file_id')

0reactions
kai23commented, Jan 17, 2017

Yes thanks for the hint. I’ll close now.

Read more comments on GitHub >

github_iconTop Results From Across the Web

fetchAll statement to return only some columns - Stack Overflow
You can add a columns call to fetch only specific columns. In this case, we request the id and name columns: $columns =...
Read more >
PDOStatement::fetchAll - Manual - PHP
PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array...
Read more >
Python cursor's fetchall, fetchmany(), fetchone() to ... - PYnative
Define the SELECT query. Here you need to know the table and its column details. Execute the SELECT query using the cursor.execute() method....
Read more >
Use SQL to Select Specific Columns From Tables - YouTube
Learn how to use the SQL Select statement to select specific columns from a table.This video is from my online course SQL Beginner...
Read more >
1. Retrieving Records - SQL Cookbook [Book] - O'Reilly
Retrieving Records This chapter focuses on very basic SELECT statements. ... You have a table and want to see values for specific columns...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found