Fetching all data

#1

I can fetch first row of the table like this;

await Database
      .table('users')
      .first()

But I want to get all records from the table. But I can’t use methods such as all or fetch. If I don’t use anything, table method returns RowDataPacket. But I need to have all data as json.

I couldn’t find anything on documentation. What am I missing?

0 Likes

#2
await Database.
  .table('users')
  .select('*')

Suppose you called users the result of the operation above; when you run:

response.send(users)

your client will get them in JSON by default, this is how AdonisJs always worked by default (because response.json is an alias for response.send and the opposite is valid)

Billal Begueradj

1 Like

#3

Simply (I have done an example previous this response)


const Database = use('Database')

after make the query inside a custom method


async index() {
    const data = await Database.table('tableName')
    return data
}

Optionally you can use the response.json() method to format the content, but by default the data will be presented in a JSON format


[{
		"id": 1,
		"name": "name1",
		"created_at": "2019-04-14T18:35:48.000Z",
		"updated_at": "2019-04-14T18:35:48.000Z"
	},
	{
		"id": 2,
		"name": "name2",
		"created_at": "2019-04-14T18:36:02.000Z",
		"updated_at": "2019-04-14T18:36:02.000Z"
	}]

1 Like