如何使用 CakePHP3 获取关联的 belongsToMany 实体

How to fetch associated belongsToMany entities with CakePHP3

我有 Users 和 Courses table 有 belongsToMany 关系。用户表有

$this->belongsToMany('Courses', [
    'foreignKey' => 'user_id',
    'targetForeignKey' => 'course_id',
    'joinTable' => 'courses_users'
]);

CoursesTable 有

$this->belongsToMany('Users', [
    'foreignKey' => 'course_id',
    'targetForeignKey' => 'user_id',
    'joinTable' => 'courses_users'
]);

现在,我想获取 user_id 的课程。在我的 CoursesController 中,我尝试了

public function myCourses()
{
    $id = $this->Auth->user('id');
    $courses = $this->Courses->find('all',
        ['contain' => ['Users'],
        'condition' => ['Courses.user_id' => $id]
        ]);
    $this->set('courses', $courses);
}

当我使用此代码调试 ($courses) 时,我收到了“(help)”=> 'This is a Query object, to get the results execute or iterate it.' 消息。我正在搜索信息并尝试了好几个小时,但我做不到。如何使用 user_id 获取课程数据?提前致谢。

如果它是与 courses_users 的联接 table 的“拥有并属于多人”(HABTM) 关联,您甚至不应该在 user_id 字段中你的课程 table.

既然我们已经确定你不能做你正在尝试的事情 (Courses.user_id),我们可以看看你认为你正在尝试什么:

 $courses = $this->Courses->find('all',
     ['contain' => ['Users'],
     //'condition' => ['Courses.user_id' => $id]
 ]);

这表示 "find all courses and any users that are associated with those courses"。

但您真正想要的(我相信)是:"find all courses that belong to this specific user"。

为此,您需要使用 matching()

根据the CakePHP book

A fairly common query case with associations is finding records ‘matching’ specific associated data. For example if you have ‘Articles belongsToMany Tags’ you will probably want to find Articles that have the CakePHP tag. This is extremely simple to do with the ORM in CakePHP:

$query = $articles->find();
$query->matching('Tags', function ($q) {
    return $q->where(['Tags.name' => 'CakePHP']);
});

所以在你的情况下,它会是这样的:

$query = $courses->find();
$query->matching('Users', function ($q) use ($id) {
    return $q->where(['Users.id' => $id]);
});