ff8mania
ff8mania

Reputation: 1770

Odata query filtering first element of a list

I have an OData query working fine, returning me something like:

    [
        {
            "Id": "ABC",
            "Related": {
                "Id": "123"
            },
            "Children": [
                {
                    "Id": "1"
                },
                {
                    "Id": "2"
                }
            ]
        },
        {
            "Id": "DEF",
            "Related": {
                "Id": "123"
            },
            "Children": [
                {
                    "Id": "3"
                },
                {
                    "Id": "4"
                }
            ]
        }
    ]

I want to filter on the first children of every object. I have no problem filtering on the value or Related (1-1 relation), but I cannot find a way to filter on the first children (0-N relation).

To filter on the 1-1 entity, I do the filter with Related/Id eq '123', but I could not find a syntax similar to Children[0]/Id eq '1'.

Any idea?

Thanks!

Upvotes: 2

Views: 5336

Answers (1)

Chris Schaller
Chris Schaller

Reputation: 16679

In OData v4, you would use $top inside the $expand option:

/odata/resources?$expand=Related,Children($top=1)

However you should always specify the sort order when you are limiting the results with $top, this example uses Id descending for no other reason than so you can see the syntax

/odata/resources?$expand=Related,Children($top=1;$orderby=Id desc)

You could also use $filter to get a specific record by id in the child,

If you had used a filter on the outer node, based on the existence of the child node, then you would also need to apply the same (or similar) filter expression to the expansion node if you didn't want to see the other children:

/odata/resources?$filter=Children/any(x:x/Id eq 4)&$expand=Related,Children($filter=Id eq 4)

Upvotes: 1

Related Questions