简体   繁体   中英

How i can add where's conditionally when i receive query params in adonis.js/node?

Actually i have this query that returns all the users in database:

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 create conditionally one way to put where in this query if i receive params.

For example, if i receive request.input('username') append one where:

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

I don't find in the documentation something that explain how i can create conditionally where's. Someone can explain me?

Tried:

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

    if(request.input('username'))
        queryUsers.where('username = %?%', [request.input('username')])

    return queryUsers.toJSON()
}

But i receive:

queryUsers.where is not a function

Actually if you look at this part of the documentation Query Builder you'll see that your query is not run until you run .fetch() or in your case .paginate() . Your code would be something like this:

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

    if(request.input('username'))
        queryUsers.where('username', '=', request.input('username'))

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

    return users
}

I fixed with the @VladNeacsu help, my finally code look this way:

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

    if(request.input('username'))
        queryUsers.where('username', '=', request.input('username'))

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

    return users
}

You can use the if helper to write a cleaner version, documented here .

async index({request}) {
    const { page, pageSize } = request.get();
    const username = request.input('username')

    const users = await User
        .query()
        .with('user')
        .if(!!username, (query) => {
           query.where('username', '=', username)
        })
        .paginate(page, pageSize)

    return users
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM