如何查询与特定连接表条目关联的数据?

问题描述

我有 2 个表,其中有很多关系:UsersTests,这是使用 bake 生成的连接表,将两个 TestsUsers 关联起来。

TestsUsers 中,我有 2 个名为 user_idtest_id 的额外字段(除了 scoredate)。第一次添加记录时,我在 TestsController 中手动制作了实体(创建一个 $test 实体,添加 test.iduser.iduser._joinData)和使用 link() 保存数据。

我在检索要编辑的记录时遇到问题。到目前为止,在索引视图(显示所有记录并具有编辑和删除操作)中,我将 3 个参数传递给编辑函数test_iduser_idTestsUsers_id。>

我用过:

$this->Tests->get(($test_id),[
    'contain' => 'Users',function ($q) use ($user_id) {
        return $q->where(['Users.id' => $user_id])  
    }
]])

结果是:

test
    (test info)
    users
        [0]
           user_id=1
           (user info)
           _joinData
                   id=1
        [1]
           user_id=1
           (user info)
           _joinData
                    id=2

问题是,我如何访问 _joinData 中的 get() 级别以使用其 ID。

附言= 我不允许加载或使用 TestsUsers 模型。 谢谢

解决方法

根据您在评论中的解释,联接表行的存在应影响是否检索 Tests,您通常需要联接关联表,并应用所需条件来过滤结果。

此外,您还需要对 contain() 应用相同的条件,因为这是一个单独的查询,除了自身之外不会影响任何内容,其结果随后将合并到 Tests 结果中PHP 级别。

一个基本的例子:

$test = $this->Tests
    ->find()
    ->contain('Users',function (\Cake\ORM\Query $query) use ($user_id,$TestsUsers_id) {
        return $query
            ->where([
                'Users.id' => $user_id,'TestsUsers.id' => $TestsUsers_id,]);
    })
    // This will join in the join table as well as the target table,// hence conditions for the former can be applied as well
    ->innerJoinWith('Users',]);
    })
    ->where([
        'Tests.id' => $test_id,])
    // Grouping is probably not required as the uniqueness of the join
    // table's primary key should already restrict things to one row
    ->group('Tests.id')
    ->firstOrFail();

另见

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...