Appearance
Relational Functions
Relational functions help resolve relationships between database tables directly in expressions.
related
Fetches related rows from a target table where a foreign key field matches a given value.
Signature: related(tableName, foreignKeyField, localValue)
| Parameter | Type | Description |
|---|---|---|
tableName | string | The slug of the target WP-Nexus table (e.g., comments, order_items). |
foreignKeyField | string | The column in the target table that references the local value (e.g., post_id, order_id). |
localValue | string/number | The 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
- The function sanitizes the table name and foreign key field.
- It looks up the physical table name in the
information_schema(matching%nexus_app_%_{tableName}). - It executes:
SELECT * FROM target_table WHERE foreign_key_field = ? ORDER BY id ASC LIMIT 100. - Returns the matching rows as an array.
Use in templates
`{ {count(related('reviews', 'product_id', row.id))}}` reviewsUse in conditions
count(related('order_items', 'order_id', row.id)) > 0Check if an order has any items.
Access related data
`{ {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)Check for related items
`{ {count(related('order_items', 'order_id', row.id)) > 0 ? 'Has items' : 'Empty order'}}`Get related item count for badges
`{ {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.