You are not logged in.
Pages: 1
Hi,
I have read documentation and I cannot find a example using an easy way to do "Has Many" relationship.
I need to implement an aproach to "Lazy loading" of nested records relation in a table.
My aproach is the next, but I don't know if is a best way to do this :
uses
System.SysUtils,
mormot,
mORMotSQLite3,
mORMotDB,
System.Contnrs,
synsqlite3static;
type
TUser = class(TSQLRecord)
private
fname: UTF8String;
fgroupid: TID;
published
property IDGroup: TID read fgroupid write fgroupid;
property Name: UTF8String read fname write fname;
end;
TGroupe = class(TSQLRecord)
private
fclient: TSQLRestServerDB;
fname: UTF8String;
fusers: TObjectList;
public
function GetUsers(aClient: TSQLRestServerDB): TObjectList;
function AddUser(aClient: TSQLRestServerDB; aUser: TUser): TID;
published
property Name: UTF8String read fname write fname;
end;
function TGroupe.GetUsers(aClient: TSQLRestServerDB): TObjectList;
begin
if Assigned(fusers) then fusers.Free;
fusers:=aClient.RetrieveList(TUser, 'IDGroup=?', [ID]);
Result:=fusers;
end;
function TGroupe.AddUser(aClient: TSQLRestServerDB; aUser: TUser): TID;
begin
aUser.IDGroup:=ID;
Result:=aClient.AddOrUpdate(aUser);
end;
var
fSQLContext: TSQLRestServerDB;
x: Integer;
user: Pointer;
group: TGroupe;
groupid: TID;
begin
try
{ TODO -oUser -cConsole Main : Insert code here }
fSQLContext:=TSQLRestServerDB.Create(TSQLModel.Create([TUser, TGroupe], 'root'),'prueba.db3');
fSQLContext.CreateMissingTables;
Writeln('Create Group');
group:=TGroupe.Create;
group.Name:='Test Group';
Writeln('Storing group');
groupid:=fSQLContext.Add(group, True);
Writeln('Adding users to group');
for x := 0 to 100 do
begin
user:=TUser.Create;
TUser(user).Name:='Name ' + x.ToString;
writeln('Added user with id : ' + Int64(group.AddUser(fSQLContext,User)).ToString);
TUser(user).Free;
end;
Writeln('Users added, freeing group');
group.Free;
Writeln('Create group again and retrieve users');
group:=TGroupe.Create;
fSQLContext.Retrieve(groupid,group);
begin
for user in group.GetUsers(fSQLContext) do
begin
writeln(TUser(user).Name);
end;
end;
Readln;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Help me!
Offline
Pages: 1