Checking For Fields To Do Conditional JOINs
As we showed in the getting started section of this documentation, the hasFields() utility allows us to check if fields under a given path were requested in the query.
The path we specify may be in dot notation or as an array of fields, and we can specify if the field should be at the root level or we want to search at any depth, which will have it do a greedy search for the fields.
Here, using dot notation:
Given the following query, this will output true to the console:
Array Notation#
As mentioned above, we may also use arrays to specify the fields we're looking for:
Greedy#
If we simply want to check, whether author was requested at all, we can also use the greedy search by setting the last argument to false:
Usage with KnexJS#
By checking if the author is being queried in advance, we can do conditional JOINs using KnexJS and avoid further SQL queries:
Playground#
QueryLive
Code
Output