何在cakephp 3.x中进行递归
我有4张桌子
users
----------
|id|name |
|1 | mick|
----------
responses
-------------------------
id|question_id| response|
1 | 1 | slim |
-------------------------
questions
------------------
id | question |
1 | body type |
-------------------
user_respopnses
----------------------------------------------
id | user_id | question_id | response_id |
1 | 1 | 1 | 1 |
----------------------------------------------
以下查询由Cakephp自动生成以获取数据
$users = $this->Users->get($id, [
'contain' => ['Responses' ]
]);
通过运行以上查询
进行响应Id Question Id Response Actions
1 1 slim View Edit Delete
我需要显示问题属性(文本)而不是问题ID但是卡住了。
用户表中定义的关系
$this->table('users');
$this->displayField('id');
$this->primaryKey('id');
$this->addBehavior('Timestamp');
$this->belongsToMany('Responses', [
'foreignKey' => 'user_id',
'targetForeignKey' => 'response_id',
'joinTable' => 'users_responses'
]);
}
调试后我得到了这个数据
'responses' => [
(int) 0 => object(App\Model\Entity\Response) {
'id' => (int) 1,
'question_id' => (int) 1,
'response' => 'slim',
'_joinData' => object(Cake\ORM\Entity) {
'response_id' => (int) 1,
'id' => (int) 1,
'user_id' => (int) 1,
'question_id' => (int) 1,
'[new]' => false,
'[accessible]' => [
'*' => true
],
'[dirty]' => [],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[invalid]' => [],
'[repository]' => 'UsersResponses'
},
实际上,User与Responses表有关系并且与Questions表没有关联,但是我们可以从第3个表“users_responses”获取它们,因为这个表有question_id,user_id,reponse_id。但是cakephp 3.x不允许递归。现在只查询命中响应表和users_response表。任何有关解决这个问题的建议或暗示都值得赞赏。
按照SQL查询实现我想要的结果(我使用了user_id = 4静态值,因为它在mysqlyog上运行)
SELECT users.id , questions.question, responses.response
FROM questions, responses, users_responses , users
WHERE
users.id = 4 AND
users_responses.user_id = 4 AND users_responses.response_id = responses.id
AND
users_responses.question_id = responses.question_id
AND
responses.question_id = questions.id;
答案 0 :(得分:0)
"递归"这里不是一个正确的词,但你想要的是
$users = $this->Users->get($id, [
'contain' => ['Responses' => ['Questions']]
]);
在手册的Eager Loading Associations部分中已经清楚地描述了这一点。