在 cakephp 3.5 中从常规表和连接表中检索数据

Retrieving data from usual and join tables in cakephp 3.5

书中的这个例子:

https://book.cakephp.org/3.0/en/orm/associations.html#using-the-through-option

class StudentsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Courses', [
            'through' => 'CoursesMemberships',
        ]);
    }
}

class CoursesTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsToMany('Students', [
            'through' => 'CoursesMemberships',
        ]);
    }
}

class CoursesMembershipsTable extends Table
{
    public function initialize(array $config)
    {
        $this->belongsTo('Students');
        $this->belongsTo('Courses');
    }
}

我可以在 students/view/N 中看到与每个学生相关的课程列表,因为我在 StudentsController 中有以下代码:

public function view($id = null)
    {
        $student = $this->Students->get($id, [
            'contain' => ['Cources']
        ]);

        $this->set('student', $student);
        $this->set('_serialize', ['student']);

    }    

如果我用 CoursesMemberships 替换课程:

public function view($id = null)
    {
        $student = $this->Students->get($id, [
            'contain' => ['CoursesMemberships']
        ]);

        $this->set('student', $student);
        $this->set('_serialize', ['student']);

    }    

并在Students/view.ctp中进行相应的修改,我可以看到相关的CoursesMemberships列表。

如何同时看到?我的意思是,StudentsController 中应该包含哪些内容,以便我可以在同一视图中(在同一 table 中更好地查看每个学生的相关课程和 days_attended 以及成绩?

使用第一个变体,即包含 Courses,连接 table 数据将在 Course 个实体 _joinData 属性 中可用。

$course->_joinData->days_attended
$course->_joinData->grade