问题描述
我有 2 个表,其中有很多关系:Users
和 Tests
,这是使用 bake 生成的连接表,将两个 TestsUsers
关联起来。
在 TestsUsers
中,我有 2 个名为 user_id
和 test_id
的额外字段(除了 score
和 date
)。第一次添加记录时,我在 TestsController
中手动制作了实体(创建一个 $test
实体,添加 test.id
、user.id
和 user._joinData
)和使用 link()
保存数据。
我在检索要编辑的记录时遇到问题。到目前为止,在索引视图(显示所有记录并具有编辑和删除操作)中,我将 3 个参数传递给编辑函数:test_id
、user_id
和 TestsUsers_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();
另见