Add Where’s in query if you receive filter parameter in Adonis/Node

Asked

Viewed 206 times

0

Currently I have this query that returns all users:

async index({request}) {
    const page = request.input('page')
    const pageSize = request.input('pageSize')
    const users = await User
        .query()
        .with('user')
        .paginate(page, pageSize)
    return users.toJSON()
}

I need to conditionally create a way to insert two Where if you have filter parameter.

For example, if you receive request.input('username') add a clause where:

.whereRaw('username = %?%', [request.input('username')])

I could not find in the documentation something that explained how to create conditionally where. Could someone give me an example?

1 answer

1


If anyone needs it, I got it done that way:

async index({request}) {
    const { page, pageSize } = request.get();
    const queryUsers = User
        .query()
        .with('user')

    if(request.input('username'))
        queryUsers.where('username', 'like', '%'+request.input('username')+'%')

    const users = await queryUsers.paginate(page, pageSize)

    return users
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.