I've been having a tough time finding an easier way to pull distinct items off a has_many inside my DObject, and then listing all of the DObjects inside. I have formed together a foreach statement, dataobjectset, and sqlquery.
Expected Results Demo here
-------------------------
Group Name
Client 1 · Client 2
Group Name
Client 3
Group Name
Client Client Client
The submitted code works as it should, however...
The reason for this post is to share what has worked for myself, and finding out if there was an easier way for myself, and others.
My Models Look Like
class Client extends DataObject {
static $has_one = array(
'ClientGroup' => 'ClientGroup'
}
}
ClientGroup.php
class ClientGroup extends DataObject {
static $db = array(
'Title' => 'Varchar(255)',
'Nice' => 'Varchar(255)'
);
static $has_many = array(
'Clients' => 'Client'
);
}
The full Query function
public function DisplayClientGroups(){
$sqlQuery = new SQLQuery();
$sqlQuery->select = array(
'clientgroup.Title AS ClientGroup',
'clientgroup.ID AS ClientGroupID',
);
$sqlQuery->from = array("clientgroup");
$sqlQuery->where = "";
$sqlQuery->distinct = true;
$rawSQL = $sqlQuery->sql();
// execute and return a Query-object
$result = $sqlQuery->execute();
$doSet = new DataObjectSet();
foreach($result as $row) {
$row['Group'] = $row['ClientGroup'];
$row['ID'] = $row['ClientGroupID'];
$getID = $row['ClientGroupID'];
$row['Clients'] = DataObject::get("Client","ClientGroupID = '$getID'");
$doSet->push(new ArrayData($row));
}
return $doSet;
}
The following is controlled on the template with
<% control DisplayClientGroups %>
<h1>$Group</h1>
<ul class='client'>
<% control Clients %>
<li>$Name <% if Location %>($Location)<% end_if %></li>
<% if Last %><% else %><li>·</li><% end_if %>
<% end_control %>
</ul>
<% end_control %>
And it works how it should. I would've like to see enumValues() work, but I kept getting a Varchar errors.
My method was discovered from the following link I found
http://tybarho.com/blog/posts/archives-dataobjectset-and-sqlquery