KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Find distinct values on a related field in entity selection
PRODUCT: 4D | VERSION: 19 | PLATFORM: Mac & Win
Published On: May 9, 2022

The distinct() function is very helpful for finding distinct (different) values in either an entity selection or a collection. However, the function is not compatible for finding distinct values of a related field in an entity selection. A runtime error is returned when passing a path to a related field into the function.

The example below causes a runtime error because the path to a related field was passed into distinct().

C_OBJECT($entSel)
C_COLLECTION($distinct_c)

$entSel:=ds.Table_1.all()
$distinct_c:=$entSel.distinct("relationLinkName.relatedFieldName") //causes runtime error

However, there are a couple ways to find the unique values in a related field.

  1. One option is to perform the disctinct() function on the related table's entity selection.

    C_COLLECTION($distinct_c)
    C_OBJECT($entSel)

    $entSel:=ds.Table_1.all()
    $distinct_c:=$entSel.relationLinkName.distinct("relatedFieldName") //no error


  2. Another option is to turn the entity selection into a collection and then perform the distinct() function on the collection.

    The example below allows finding all the unqiue values for the related field for the entity selection (after turning it to a collection).

    C_COLLECTION($entSel_c; $distinct_c)
    C_OBJECT($entSel; $ent)

    $entSel:=ds.Table_1.all()
    $entSel_c:=New collection
    For each ($ent; $entSel)
      $entSel_c.push($ent)
    End for each

    $distinct_c:=$entSel_c.distinct("relationLinkName.relatedFieldName") //no error on collection