在详细信息页面上看不到银条关系


Silverstripe relation is not visible on details page

我在模板CoursePage.ss上循环教师关系,但当我试图在CouresePage_details.ss内循环关系teachers时不工作。我做错了什么。

我有两个模型CoursesTeachers

  1. Course可以有很多老师
  2. Teacher可以有一个课程

Courses.php

class Courses extends DataObject 
{
     private static $many_many = array(
        'Teachers' => 'Teachers',
    );
}

Teachers.php

class Courses extends DataObject 
{
     private static $belongs_many_many = array(
        'Courses ' => 'Courses ',
    );
}

CoursesPage.php

class CoursesPage extends Page
{
}
class CoursesPage_Controller extends Page_Controller
{
    public static $allowed_actions = array(
        'details'
    );
    // Show specific course
    public function details(SS_HTTPRequest $request)
    {
        $c= Courses::get()->byID($request->param('ID'));
        if(!$c) {
            return $this->httpError(404, "Courses not found");
        }
        return array(
            'Courses' => $c,
        );
    }
    // Courses list
    public function CoursesList ()
    {
       $c = Courses::get()->sort('Featured', 'DESC');
        return $c;
     }
}

CoursesPage.ss

在这个文件中我只是循环课程,没有什么重要的。这里是课程和老师的循环列表。这里的老师循环工作完美只是不工作的细节模板。

CoursesPage_details.ss

有个问题。当我显示有关特定course的详细信息时,我想循环teachers,这与本课程相关,但我一直得到NULL返回Teachers does not exist

<section class="course-details">
    <h2>$Courses.Name</h2> <!-- Work -->
    <p>$Courses.Descr</p>
    <ul class="teachers-list">
        <% if $Teachers %> <!-- Not work here, but on CoursePage.ss work -->
            <% loop $Teachers %>
                 $FirstName
            <% end_loop %>
        <% else >
           Teachers does not exist
        <% end_if %>
    </ul>
</section>

您需要使用$Courses.Teachers代替…或者您可以通过使用<% with $Courses %>将范围更改为Courses。所以你的模板看起来像这样:

<section class="course-details">
<% with $Courses %>
    <h2>$Name</h2>
    <p>$Descr</p>
    <ul class="teachers-list">
        <% if $Teachers %> 
            <% loop $Teachers %>
                 $FirstName
            <% end_loop %>
        <% else >
           Teachers does not exist
        <% end_if %>
    </ul>
<% end_with %>
</section>

这样做的原因是:您将Course数据对象作为名为Courses的参数传递给模板。正是这个DataObject与Teachers有关系,因此您需要使用$Courses.Teachers或如上所述更改范围。默认情况下,您仍然在CoursesPage的范围内。