【问题标题】:How to fetch associated belongsToMany entities with CakePHP3如何使用 CakePHP3 获取关联的 belongsToMany 实体
【发布时间】:2017-07-15 23:20:23
【问题描述】:

我有带有 belongsToMany 关系的用户和课程表。 UserTable 有

$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)' => '这是一个 Query 对象,让结果执行或迭代它。'信息。我正在搜索信息并尝试了很多小时,但我做不到。如何使用 user_id 获取课程数据?提前致谢。

【问题讨论】:

    标签: php cakephp cakephp-3.0


    【解决方案1】:

    如果它是与 courses_users 连接表的多属性关联 (HABTM) 关联,那么您的 Courses 表中甚至不应该有 user_id 字段。

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

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

    这表示“查找所有课程以及与这些课程关联的任何用户”。

    但你真正想要的(我相信)是:“找到属于这个特定用户的所有课程”。

    为此,您需要改用matching()

    根据the CakePHP book

    一个相当常见的关联查询案例是查找记录 “匹配”特定的相关数据。例如,如果您有“文章 属于ToMany 标签”,您可能希望找到具有 CakePHP 标记。这在 ORM 中非常简单 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]);
    });
    

    【讨论】:

    • 非常感谢!这正是我问的!一件事是我在“function ($q)”之后需要“use ($id)” $query->matching('Users', function ($q) use ($id) { return $q->where([ 'Users.id' => $id]); });
    • 很好的解释!
    猜你喜欢
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 2015-09-27
    • 2017-02-16
    • 2015-11-15
    • 1970-01-01
    • 2017-03-02
    • 2022-01-26
    相关资源
    最近更新 更多