How to select records from mysql


#1

i want to show one of the users that has id=105 from mysql users table.
how i can do that?
please write complete simple model/view/routing and controller to do this.
i am a beginner :wink:


#2

Here you have a little example

First create this file from the command line inside your adonis app


adonis make:controller UserController

Now go to .env file at the root of your project and change credentials in the mysql zone, for your owns, also change the DB_CONNECTION to mysql since sqlite is the default

Now go to app/config/database.js and change this

connection: Env.get('DB_CONNECTION', 'sqlite'),

to this

connection: Env.get('DB_CONNECTION', 'mysql'),

After in your routes in start.routes.js write the following


Route.get('/fetchUser/:id', 'UserController.index')

CLARIFICATIONS

  • fetchUser is the URL to write in your web browser
  • UserController is the name for the Controller
  • index is the method to encapsulate the query
  • :id is to indicate a param in your URL

Now go to app/Models/User.js and write this to invoke the table


static get table() {
      return 'myTable'
}

CLARIFICATIONS

  • static get table(){} is the default method to return the table name
  • myTable must be chaged for your table name

Now go to app/Controllers/UserController.js and write the following at the top of this file


const User = use('App/Models/User')

After inside the class write this


async index( {params} ) {
           const id = params.id
           const user = await User.find(id)
           return user
}

CLARIFICATIONS

  • You need to use {params} to get the id, don¿t forget the {} curly braces
  • When I do this const id = params.id I get the id from the URL and I assign it to a const called id
  • Finally I make use of the Lucid method find()

Now from your command line run your app with this command


adonis serve --dev

Now if you go to localhost:3333/fetchUser/105 data is ready @majidghafoorzade


#3

if i want to show user using id parameter like this :

127.0.0.1:3000/user/106

how i can do this?


#6

@majidghafoorzade please if this was helpful for you then mark the answer as the correct one, thanks


#7

You’ll need to change your route.

Route.get('/user/:id', 'UserController.index')