2017-05-03 38 views
0

我的问题是当我调用$ data时,我无法检索评论,它像这样返回,为什么评论不返回?Cakephp 2x无法检索hasMany关系数据

Array(
[0] => Array 
    (
     [Event] => Array 
      (
       [id] => 1 
       [url_id] => 22cbb58298af0fe62284324ccc020023 
       [name] => 高尾山ハイキング 
       [date] => 2017-05-06 00:00:00 
       [memo] => 行こうぜ 
       [is_available] => 1 
       [created] => 2017-05-03 21:15:30 
       [modified] => 2017-05-03 21:15:30 
      ) 

     [Comment] => Array 
      (
      ) 

    )) 

这是事件控制和事件的hasMany评论,由我是 已经在型号

$data = $this->Event->find('all',[ 
      'conditions' => [ 
       'Event.url_id' => $eventURL 
      ], 
      'contain' =>[ 
       'Comment'=>[ 
        'conditions' => ['Comment.event_id' =>$eventURL], 
       ], 
      ], 
     ]); 
+0

我认为这是错误的''条件'=> ['Comment.event_id'=> $ eventURL],'评论表是否在'event_id'列有22cbb58298af0fe62284324ccc020023'? –

+0

分享你的两个表结构。所以我们可以了解它们之间的关系。从代码来看问题与关联有关。原因评语表的 –

+0

有外键的事项标识,继承人的表 CREATE TABLE'comments'( \t'id' INT(10)UNSIGNED NOT NULL AUTO_INCREMENT, \t'user_id' INT(10)UNSIGNED NOT NULL, \t 'event_id' VARCHAR(255)NOT NULL, \t'content' TEXT NOT NULL, \t'created' TIMESTAMP NULL DEFAULT NULL, \t'modified' TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, \t PRIMARY KEY('id' ), \t INDEX'索引2'('event_id') ) COLLATE ='utf8mb4_general_ci' ENGINE = InnoDB AUTO_INCREMENT = 20 ; – Tuang

回答

1

完成一些设定了这样您不必手动添加您的contain密钥内的foreign_key。

如果你的模型设置正确,你有hasMany记录EventComment表,这应该给你,你期待什么。

$data = $this->Event->find('all', [ 
    'conditions' => [ 
     'Event.url_id' => $eventURL 
    ], 
    'contain' =>[ 
     'Comment' 
    ] 
]); 

如果有一个Comment数据库内与1event_id你应该得到它。

如果你不这样做,请设置Configure::write('debug', 2)并检查你的SQL调试输出,生成什么查询。