如何在Silverstripe中将自定义SQL查询显示为模板循环?

时间:2017-11-08 21:04:40

标签: php silverstripe

我试图让以下SQL查询显示为Silverstripe循环:

public function FilteredCompanyDivisions($SectionID)
{
  $query = DB::query(
    'SELECT "CompanyDivision"."Title", "Office_CompanyDivisions"."DivisionPhoneNumber"
    FROM "CompanyDivision"
    LEFT JOIN "Office_CompanyDivisions" 
      ON "CompanyDivision"."ID" = "Office_CompanyDivisions"."CompanyDivisionID"
    LEFT JOIN "Section_SectionCompanyDivisions" 
      ON "Section_SectionCompanyDivisions"."CompanyDivisionID" = "CompanyDivision"."ID"
    WHERE "Section_SectionCompanyDivisions"."SectionID" = '.$SectionID.'
      AND "Office_CompanyDivisions"."OfficeID" = '.$this->ID);

通过以下代码运行它会返回一个数据对象:

$output = array();
if ($query) {
    foreach ($query as $item) {
        $output[] = array(
            'Title' => $item['Title'],
            'DivisionPhoneNumber' => $item['DivisionPhoneNumber']
        );
    }
}

    return $output;
}

通过Debug::show($output);返回的数据对象如下所示:

0 =
    Title =
    Widget Fluffing
    DivisionPhoneNumber =
    06 666 6666

然而,以下模板代码无效:

<% loop FilteredCompanyDivisions($Top.ID) %>
  <li>
    <i class="icon-phone"></i> 
    <a href="tel:$DivisionPhoneNumber">$DivisionPhoneNumber</a> - $Title
  </li>
<% end_loop %>

...并返回此HTML:

<li><i class="icon-phone"></i> <a href="tel:"></a> - </li>

我做错了什么?如何在Silverstripe中将自定义SQL显示为模板循环?

1 个答案:

答案 0 :(得分:2)

您需要使用ArrayListArrayData而不是返回php数组。

$output = ArrayList::create();
if ($query) {
    foreach ($query as $item) {
        $output->push( ArrayData::create(array(
            'Title' => $item['Title'],
            'DivisionPhoneNumber' => $item['DivisionPhoneNumber']
        )));
    }

    return $output;
}