Problem with relationships (specific columns)

#1

I’m trying show some specific columns in relationship. If i don’t put that specific columns, works perfectly, if i put don’t show anything.

without specific columns and working perfectly:

async index ({ request, response, view }) {
    const testes = await Teste.query()
      .with('user')
      .fetch()

    return testes
  }

{ method: ‘select’,
options: {},
timeout: false,
cancelOnTimeout: false,
bindings: [],
__knexQueryUid: ‘748f1789-81eb-48db-a400-853bcd4c9861’,
sql: ‘select * from “testes”’ }
{ method: ‘select’,
options: {},
timeout: false,
cancelOnTimeout: false,
bindings: [ ‘rafael.mignoni’ ],
__knexQueryUid: ‘40f28b09-e892-464d-a02f-bae3427604dc’,
sql:
‘select * from “usuario_perfil” where “usuario_perfil”.“samaccountname” in (?)’ }

[
{
“id”: 1,
“usuario”: “rafael.mignoni”,
“title”: “tituloasdsadasd”,
“description”: “descriptionasdasdada”,
“created_at”: null,
“updated_at”: null,
“user”: {
“cod_empresa”: 1,
“primeiro_nome”: “RAFAEL”,
“ultimo_nome”: “MIGNONI”,
“email”: "rafael.mignoni@jorlan.com",
“telefone”: null,
“ramal”: null,
“celular”: null,
“email_pessoal”: null,
“samaccountname”: “rafael.mignoni”,
“cidade”: “GOIANIA”,
“uf”: “GO”
}
}
]

with specific columns and dont showing nothing:

async index ({ request, response, view }) {
    const testes = await Teste.query()
      .with('user', builder => {
        builder.select(['primeiro_nome', 'ultimo_nome'])
      })
      .fetch()

    return testes
  }

{ method: ‘select’,
options: {},
timeout: false,
cancelOnTimeout: false,
bindings: [],
__knexQueryUid: ‘9dbd48b3-3797-4b3d-81b9-d2bb5ca966cb’,
sql: ‘select * from “testes”’ }
{ method: ‘select’,
options: {},
timeout: false,
cancelOnTimeout: false,
bindings: [ ‘rafael.mignoni’ ],
__knexQueryUid: ‘d49203e3-f1f4-40c0-8964-4058690ad2bb’,
sql:
‘select “primeiro_nome”, “ultimo_nome” from “usuario_perfil” where “usuario_perfil”.“samaccountname” in (?)’ }

[
{
“id”: 1,
“usuario”: “rafael.mignoni”,
“title”: “tituloasdsadasd”,
“description”: “descriptionasdasdada”,
“created_at”: null,
“updated_at”: null,
“user”: null
}
]

0 Likes

#2

Can you check that you have included the foreign key field in the selection otherwise Lucid can not make the relationship.

0 Likes

#3

When you’re using eager loading concept you will need to include the FK name, so your code needs to be in this way


async index ({ request, response, view }) {
    const testes = await Teste.query()
      .with('user', builder => {
        builder.select(['primeiro_nome', 'ultimo_nome', 'foreignKeyName'])
      })
      .fetch()

    return testes
  }

CLARIFICATIONS

  • foreignKeyName is the place where you need to write the name of your foreign key
0 Likes