LunaQL docs are incomplete.
How To
Relationships

Relationships

Introduction

LunaQL is a NoSQL database that supports relationships. This means, you don't have to have nested documents for your collections. Instead, you can just create a new collection and join it with your main collection.

Defining Relationships

Relationships in LunaQL are defined as nested queries.

One To One

A one-to-one relationship exists when one row in a collection may be linked with only one row in another collection and vice versa. For example, a user might be associated with one address:

queries/users/all.lunaql
query({
	from({
		users: {
			belongsTo: {
				address: {
					where: ["_id", "==", "$.user_id"]
				};
			};
		};
	});
});

One To Many

A one-to-many relationship exists when one row in collection A may be linked with many rows in collection B, but one row in collection B is linked to only one row in collection A. For example, a user may have an infinite number of posts:

queries/users/all.lunaql
query({
	from({
		users: {
			hasMany: {
				posts: {
					where: ["user_id", "==", "$._id"]
				};
			};
		};
	});
});

Queries In Relationships

When defining your relationships, you may want to only return documents that match your criteria. For example, you may only want to return a user's posts if they have been published:

queries/users/all.lunaql
query({
	from({
		users: {
			hasMany: {
				posts: {
					where: [
						["user_id", "==", "$._id"],
						["is_published", "==", true]
					]
				};
			};
		};
	});
});

We can also filter out documents that didn't meet the criteria based on a relationship using the hideIfEmpty method. For example, you may choose not to return a users document if the hasMany relationship doesn't return anything:

queries/users/all.lunaql
query({
	from({
		users: {
			hasMany: {
				posts: {
					where: [
						["user_id", "==", "$._id"],
						["is_published", "==", true]
					]
				};
			};
 
			hideIfEmpty(["posts"]);
		};
	});
});
 

This will hide all the users documents that didn't meet the posts relationship criteria.