How do I access images for use in a template from ArrayList obtained with SQLSelect?

Silverstripe Version: 4


I have a DataObject called Country with Images on each record, that are uploaded using the UploadField::create(‘Photo’) static method in the Admin.

In my CountryDetailPage controller, I use SQLSelect to obtain records by one of the DataObject’s fieldnames (slug), like so:

$sqlQuery = new SQLSelect();
$results = $sqlQuery->execute();
//setup our blank DataObjectSet to push SQL result data into it.
$Country = ArrayList::create();
foreach($results as $result) {
  //move the SQL result data to the DataObjectSet
  $CountryTitle = $result['Title'];
  $CountryID = $result['ID'];

Then, in the template loop, I’m trying to show the $Photo, but it’s not returning anything, which must be because the SQLQuery only returns a PhotoID.

Not Working:

<% with $Photo %>
  <img  src="$Photo.URL"  />
<% end_with %>

Is it possible to access the actual photo, in some way, for use in the template? If so, how do I do it?


What relationship does the image have to your DataObject? If you really need to use SQL, then you’ll need to manually add the joins to the File table, but how you do that will depend on how the photo is related to the object.

By far the simplest way to do it, is just to use the ORM to get the data. If you do that, then it will deal with the joins and make the photo available in the template without any extra work.

Country::get()->filter(['Slug' => $slug])->first(); would you get the object… then in the template you can just access all the properties, including the Photo data

These are on the Country Class.

private static $has_one = [			
  'Photo' => Image::class,

private static $owns = [

OK. So the real question is, do you need to use SQL manually? If you use the ORM, you can turn all that code into a one-liner :slight_smile:

@Tim - thank you for the advice. I’m going to try rewriting all of these queries using the ORM. Now that I’m taking another look at it, that will work way better., I guess I went too far down the rabbit hole with those SQLSelects. :thinking:

You’ll probably find it saves you time in the long run though. :alarm_clock: :+1: