Can AdonisJS 4.1.0 support conditional queries?

I am exploring the capabilities of AdonisJs query builder by referring to their documentation at

Currently, I am attempting to replicate a scenario similar to the one demonstrated under the 'Conditional Queries' section:

const query = Database.table('users')
if (username) {
  query.where('username', username)
}

Unfortunately, when implementing this in my backend code, it results in an error.

My objective is to execute conditional where queries. There are situations where I require the where clause, while in other cases, all data needs to be retrieved based on a boolean value without applying any where conditions.

I have observed that the 'query' variable (in the example above) can only be chained effectively when connected to the Database class directly. Attempting to save it as a standalone variable leads to errors, such as query.where(...).

At present, my workaround involves creating separate queries using the Database class for all possible combinations of 3 boolean conditions, resulting in 9 different queries. However, as I anticipate more conditions in the future, this approach may become impractical.

Is there a more efficient way to handle conditional where queries in AdonisJs?

P.S: While I am aware that multiple fields can be included in a single where clause like

.where({ field1: true, field2: false})
, this is not directly related to my current issue.

Answer №1

forget about it,

let search = Database.table('employees')
if (name) {
  search.where('name', name)
}

It's effective. I mistakenly used await on Database which wasn't necessary.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When working with VueJS and Vuex, using the splice method to replace an item (object) in an array stored in Vuex does not trigger a re-render of the

I have an array of records. Each record consists of an object with _id (mongo id), title, and value (value is an object with amount and currency). When displaying the list of records using v-for, the ':key' for each item in the list is set to th ...

Using React JS to iterate over an array and generate a new div for every 3 items

It's a bit challenging for me to articulate my goal effectively. I have a JSON payload that looks like this: { "user": { "id": 4, "username": "3nematix2", "profile_pic": &qu ...

Transform an array of objects into a nested tree structure with Javascript

I am currently facing a challenge with handling a complex json file using javascript to structure it hierarchically. My goal is to convert an array of objects into a deeply nested array, where there can be multiple divNames with varying categories and subc ...

Retrieving information from an array and displaying it dynamically in Next.js

I've been diving into the Next.js framework lately and I've hit a roadblock when it comes to working with dynamic routes and fetching data from an array. Despite following the basics of Next.js, I'm still stuck. What am I looking for? I ne ...

Create a dynamic image showcase using PHP or JavaScript

So I have a large collection of car photos organized in a structure similar to this (this is just a fictional example to illustrate my idea): Cars > Audi > Sports cars > '5 pictures' Cars > Audi > Family cars > '3 pictur ...

Updating ng-table within an Angular controller

Having encountered an unusual issue with ng-table. Here is a snippet of code from my controller: this.category = "Open"; this.category = ["Open", "Accepted", "Rejected"]; this.dataItems = []; var _this = this; this.$scope.$watch("vm.category", function( ...

Leveraging AJAX for transmitting form information to a php script without relying on jQuery

I want to explore AJAX by implementing a basic form data submission to a php script and database. For educational purposes, I've reached a standstill after hitting the "Create Profile" button with no action. Could someone spot any syntax or structural ...

Ways to append each list item from one unordered list to the end of another based on their unique styles

I am in the process of making a website responsive and I am faced with the task of combining two different menus. In order to achieve this, I need to transfer all list items (li) from one unordered list (ul) to another. Provided below is a simplified vers ...

Utilizing ASP.NET MVC Kendo Grid to invoke a controller method via JavaScript

To implement a custom modal confirmation popup, I need to invoke the method .Destroy("Remove", "Attachment") from javascript. How can I trigger the Remove method in javascript? I have identified where I would like to make this call in the code snippet. Add ...

Learn how to dynamically enable or disable the add and remove buttons in the PrimeNG PickList using Angular 2

I'm currently learning Angular 2 and I'm working on creating a dual list box using PrimeNG's pickList component (https://www.primefaces.org/primeng/#/picklist). Within the pickList, I have table data with 3 columns, along with ADD and REMO ...

Ajax is unable to reach a file located in the directory UP from the application's main folder

Here is the ajax call I am using: <script> jQuery(document).ready(function(){ jQuery('#compare_btn').click(function(event){ event.preventDefault(); var id=jQuery('#compare_btn').attr('name'); alert(id); ...

How can you direct a user to a specific page only when certain conditions are met?

Currently using React in my single page application. I have a good grasp on how Routes function and how to create a PrivateRoute. The issue arises when I need to verify the user's identity before granting access to a PrivateRoute. My attempt at imple ...

What are the steps to ensure that this iframe adjusts perfectly to the page in terms of both vertical and horizontal dimensions

I have a sandbox from Material UI that you can view at this link: https://codesandbox.io/s/material-demo-forked-c8e39?file=/demo.js Upon loading the page, an iframe displays some HTML content. Although the width fits perfectly, there are two vertical scro ...

After performing an action with Redux, the error message ""Cannot access properties of 'undefined'" is displayed

I am currently developing a Shopping List App using React/Redux. I am facing issues with removing items from a list. When I trigger the 'removeItem' action, the page no longer recognizes the object that represents the list (which was originally s ...

Support for both Fetch API and XMLHttpRequest across browsers is imperative for seamless data retrieval and

Currently, I am diving into the world of ajax programming techniques. However, I recently discovered that the XMLHttpRequest is deprecated and now I must transition to using the Fetch API. The catch is, according to MDN, the Fetch API is still considered e ...

struggling to send variables to jade templates with coffeescript and express.js

As a newcomer to node and express, I am currently building the front end of an application that utilizes jade as its templating engine. Despite extensive searching online and within this community, I have not been able to find a solution to a particular is ...

Using Regular Expressions in Javascript

I have gone through numerous posts with this title, but so far, none of them have addressed my specific query... My requirement is to utilize regex in the following format: "/^ user provided input $/i". The user can include the special regex character * e ...

Is it possible to eliminate the array from a property using TypeScript?

Presenting my current model: export interface SizeAndColors { size: string; color: string; }[]; In addition to the above, I also have another model where I require the SizeAndColors interface but without an array. export interface Cart { options: ...

How can parameters be included in ng-href when using ng-click?

So I have this list of products and I want to pass the current product id when clicking on ng-href by using a function with ng-click in the ng-href. This is what my html file looks like: <div class="agile_top_brands_grids" ng-model="products" ng-repe ...

What is the best way to extract and count specific values from a JSON file using JavaScript?

My JSON data looks like this: /api/v1/volumes: [ { "id": "vol1", "status": "UP", "sto": "sto1", "statusTime": 1558525963000, "resources": { "disk": 20000000 }, "used_resources": { "disk": 15000000 }, "las ...