CakePHP:findById()with Containable不返回预期的关联

weixin_38116227 2019-09-12 11:16:00
这是我的模特: class Question extends AppModel { public $hasMany = array( 'CaseQuestions' => array('className'=>'Question', 'foreignKey'=>'parent_id') ); public $hasOne = array( 'CaseStudy' => array('className'=>'Question', 'foreignKey'=>'parent_id') ); 这是我的控制器中的动作: public function admin_delete_case_question($question_id) { $this->Question->Behaviors->load('Containable'); $this->Question->contain( array('CaseStudy')); $question = $this->Question->findById($question_id ); debug($question); exit; 上面的调试返回如下内容: array( 'Question' => array( 'id' => '78', 'nickname' => '', 'content' => 'sdgsdfgs', 'type' => 'CQ', 'option1' => 'sdfgsdfg', 'option2' => '', 'option3' => '', 'option4' => '', 'time' => '-1', 'difficulty' => '0.0000', 'slope' => '0.0000', 'chance' => '0', 'experiment' => false, 'created' => '2013-05-02 16:30:29', 'modified' => '2013-05-02 16:30:29', 'status' => null, 'perm_id' => '76', 'notes' => null, 'is_deleted' => false, 'answer_id' => '0', 'parent_id' => '77', 'order' => null ), 'CaseStudy' => array( 'id' => null, 'nickname' => null, 'content' => null, 'type' => null, 'option1' => null, 'option2' => null, 'option3' => null, 'option4' => null, 'time' => null, 'difficulty' => null, 'slope' => null, 'chance' => null, 'experiment' => null, 'created' => null, 'modified' => null, 'status' => null, 'perm_id' => null, 'notes' => null, 'is_deleted' => null, 'answer_id' => null, 'parent_id' => null, 'order' => null ) ) 我不明白为什么CaseStudy数组都是NULL,因为当我在DB中查看该记录(id 77)时,所有数据都是正确的.我究竟做错了什么?
...全文
27 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38133933 2019-09-12
  • 打赏
  • 举报
回复
在你的例子中…问题有一个CaseStudy;这意味着问题是父母. 根据您的数据,您的问题有一个parent_id,所以我假设您实际上意味着CaseStudy是父,而Question是孩子.看起来您的关联实际上是倒退的(通常父节点不会有parent_id). 用belongsTo替换你的hasOne关联: public $belongsTo = array( 'CaseStudy' => array('className'=>'Question', 'foreignKey'=>'parent_id') ); 这将确保CaseStudy是父级,而Question是孩子. 通过它当前设置的方式,CakePHP正在尝试寻找一个父类与您的Question.id相等的CaseStudy;因为你的数据库中没有任何类似的数据,CakePHP找不到任何内容并返回空值.实际上,CaseStudy实际上是父,而Question的parent_id等于CaseStudy.id

433

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧