【问题标题】:Retrieving data from usual and join tables in cakephp 3.5从 cakephp 3.5 中的常用表和连接表中检索数据
【发布时间】:2017-08-17 06:43:17
【问题描述】:

在本书的这个例子中:

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 替换 Courses:

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

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

    }    

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

如何查看两者?我的意思是,StudentController 中应该包含什么,以便我可以在同一个视图中(在同一张表中更好)看到每个 Student,相关的 Courses 以及 days_attended 和 Grade?​​p>

【问题讨论】:

    标签: cakephp jointable


    【解决方案1】:

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

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

    【讨论】:

    • 我有办法使用生成的 Cake 代码从这个表“CoursesMemberships”中添加、查看、编辑和删除吗?索引有效,它正确列出了所有条目,其余的最终给出了“InvalidPrimaryKeyException”。
    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多