neManiac
neManiac

Reputation: 355

Optimal way to search for an object by using a unique value of one of it's properties

I have an object with a property that has unique values. It might not be a good reason, but this property isn't my ID because it is a list, and the display value consists of non-printing characters.

I would like to check for existence of an object with a specific value of this property. The options I have thought of so far are making it the ID and then using the built in %ExistsID method, using a SQL query and manually searching the global for the appropriate subscript.

The problem with the first solution is I prefer to have a human readable ID. If I am being silly, please say so.

The problem with the 2nd approach is that it seems to me that while SQL is good for stuff like this, in this particular case it seems to me that I'm setting in motion this cumbersome mechanism with lots of overhead to get at a result which I should be able to get easier. Again, I might just be silly about this.

The problem with the last one is that the value, being a LB consisting mostly of numbers, is stored as $c(x,y,z). I'm not sure how to search for this (i.e. how to get from my list to this). Also, it seems kind of messy and that I'm going too low-level.

I feel like there ought to be a simpler OO way to fetch objects based on a unique (indexed) value, and I'm almost sure there is but I can't seem to find it in the docs. A autogenerated %PropertyExists(UniqueValue) would be nice.

Maybe I should write my own generator method? Any advice is appreciated.

Upvotes: 3

Views: 157

Answers (2)

DAiMor
DAiMor

Reputation: 3205

If you look at documentation, you will find, that every unique index in a class, has some generated method, such as Open and Exists and Delete. And with any of this methods you can Open any object by known unique values.
So, if you have index like this

Index SomeInd On (Prop1, Prop2) [ Unique];

you can open object, so

set obj=##class(your.class).SomeIndOpen(prop1val, prop2val)

or check if such object already exists, and get and ID for this object.

if ##class(your.class).SomeIndExists(prop1val, prop2val, .id) {
    //
}

I hope it would be enough for you, if not, feel free to ask more.

Upvotes: 4

clementgamache
clementgamache

Reputation: 100

You can use a more simple SQL query using the COUNT() function and then return if the count is of 1. To do so, take a look at this thread: Select count(*) from result query

Upvotes: 2

Related Questions