Abraham Wasswa · May 1, 2022

Help to Accessing Foreign key property using JSON Object

Given I have a property 

Class All.AllBooks Extends %Library.Persistent

Property ID As %Integer;

Property Title As User.Book;



In the class method

ClassMethod GetABookById(id As %Integer) As %Status

SET MyBooks = ##class(All.Allbooks).%OpenId(id)

SET obj = {

     "ID" : (MyBooks.%Id())

     "Title" : (MyBooks.Title)



Quit 1


How do Access the foreign key in JSON() data

Product version: IRIS 2019.4
0 251
Discussion (7)1
Log in or sign up to continue

I guess you look for this:

ClassMethod GetABookById(id As %Integer) As %Status
 SET MyBooks = ##class(All.Allbooks).%OpenId(id)
 SET obj={} 
 set obj.ID=MyBooks.%Id()
 set obj.Title=MyBooks.Title
 WRITE obj.%ToJSON()
 Quit 1

MyBooks.Title is just a reference to User.Book

@Robert.Cemper1003 how do I go about creating a new Item given I want to save the ID from the Title class. I'm stuck at that.

SET obj = ##class(%DynamicObject).%FromJSON(%request.Content)

SET task =  ##Class(All.Allbooks).%New()

SET task.Title = Obj.TitleID

DO task.%Save()

Thank you for your help

You depend on the structure of the dynamic object you compose in the 1st line.
if it has a property TitleID  it will work. (using obj.TitleID   lower case!!)

But in your question, it is not clear what Title Class refers to.
I see All.Allbooks and somewhere User.Book and also %request  and no other class around

@Robert Cemper sorry for the confusion I'm trying to access the ID in Book class I used Title as a property name in Allbooks class.

In my structure of Dynamic object, I am trying to call content from a new JSON data to create a new Book title with the ID from Book class. I'm using Title as a foreign key property.

  • so your obj is a DynamicObject and looks something like { "ID":17, "Title": 44 }
  • class All.Allbooks has this Property Title As User.Book. 
  • To set it you need an oref !!

therefore to create the required oref :

SET task.Title = ##class(User.Book).%OpenId(obj.Title)

@Robert Cemper 
Thank you taht solves the problem for the OREF the challenge I find around it it doesn't post the data to the database the object I have can look like this


I want it to store the following in the database

ID - > autoincrement - this I know how to do it.
Title -> I want to store the ID where Value is "LEARNING CAHE REST API" in the All.Allbooks table

Thank you for all you help. it has open my eyes more. sorry if I ask the obvious questions I'm A C#/ASP.NET developer trying to learn Objectscript/CACHE/MUMPS