Skip to content

Relational Functions

Relational functions help resolve relationships between database tables directly in expressions.

Fetches related rows from a target table where a foreign key field matches a given value.

Signature: related(tableName, foreignKeyField, localValue)

ParameterTypeDescription
tableNamestringThe slug of the target WP-Nexus table (e.g., comments, order_items).
foreignKeyFieldstringThe column in the target table that references the local value (e.g., post_id, order_id).
localValuestring/numberThe value to match against (typically row.id).

Returns an array of matching rows from the target table, ordered by id ASC, limited to 100 rows.

`{ {count(related('comments', 'post_id', row.id))}}` comments
// "5 comments"

How it works

  1. The function sanitizes the table name and foreign key field.
  2. It looks up the physical table name in the information_schema (matching %nexus_app_%_{tableName}).
  3. It executes: SELECT * FROM target_table WHERE foreign_key_field = ? ORDER BY id ASC LIMIT 100.
  4. Returns the matching rows as an array.

Use in templates

`{ {count(related('reviews', 'product_id', row.id))}}` reviews

Use in conditions

count(related('order_items', 'order_id', row.id)) > 0

Check if an order has any items.

`{ {join(related('tags', 'post_id', row.id), ', ')}}`

This would need the related rows to have a string representation -- typically you would access a specific field with additional processing.

Examples

Show comment count on a post list

`{ {row.post_title}}` (`{ {count(related('comments', 'post_id', row.id))}}` comments)
`{ {count(related('order_items', 'order_id', row.id)) > 0 ? 'Has items' : 'Empty order'}}`
`{ {count(related('tasks', 'project_id', row.id))}}`

TIP

The related() expression function is convenient for simple counts and checks in templates. For full access to related data (displaying related items in a repeater, joining data for processing), use the Related Items pipeline node or the Lookup node instead.

WARNING

The related() function makes a database query each time it is called. Avoid using it inside repeater templates with large datasets, as it generates one query per row. For better performance, use the Lookup pipeline node which batch-queries all related items in a single SQL statement.