records_related()
Get the records in another table that are linked (via a lookup field) to a given record.
Syntax
records_related(sourceTable, recordId, relatedTable)
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
sourceTable |
string | yes | Table name or id of the record you start from. |
recordId |
int | yes | The source record's primary key. |
relatedTable |
string | yes | Table name or id of the related records to fetch. |
Returns
A list (array) of records from relatedTable that link back to the source record.
Example
$orders = records_related("customers", $record["_meta"]["id"], "orders");
sys_log($record["name"] . " has " . count($orders) . " orders");
foreach ( $orders as $o ) {
sys_log(" - " . $o["title"] . ": $" . $o["amount"]);
}
Example output
[
["title" => "Order #1001", "amount" => 250, "_meta" => ["id" => 501, "title" => "Order #1001"]],
["title" => "Order #1002", "amount" => 80, "_meta" => ["id" => 502, "title" => "Order #1002"]]
]
Notes
- The related table must have a lookup field that points to the source table.
- Throws if the source record can't be found.
See also: records_query()