Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Adding related fields in DataList


Go to End


2 Posts   1103 Views

Avatar
jbardnz

Community Member, 1 Post

29 January 2015 at 1:44pm

Hello

I am trying to append a relationship onto a DataList so I can return it as JSON, here is an example of what I mean:

I am getting my model like so:

$enteries = Entry::get();

and then to return them as JSON I do:

return json_encode($enteries->toNestedArray());

My Entry model has a has_one relation with an Image, I want to return a path to that image as part of my JSON call, what is the best way to achieve this?

Cheers

Avatar
martimiz

Forum Moderator, 1391 Posts

30 January 2015 at 3:30am

Using the ORM you could do something like this (unfortunately a join on get() will not return related tablefields):

$list = new ArrayList();
$enteries = Entry::get();
foreach ($enteries as $entry) {
	$entry->ImagePath = $entry->Image()->Filename;
	$list->push($entry);
}
$array = $list->toNestedArray();
$json = json_encode($array);

This might maybe get a bit slow if you have lots of entries, in which case you could use SQLQuery to perform a join on the File table - but then you'd have to walk through the results and more or less build the array by hand. Not a big issue, just takes some more coding...