简体   繁体   English

如何使用cakephp从两个相关的表中检索数据?

[英]How to retrieve data from two related tables using cakephp?

I have two tables in a database, one as event(eventID,name,location), and the other one as eventImages(id,eventID,path). 我在数据库中有两个表,一个作为事件(eventID,名称,位置),另一个作为事件图像(id,eventID,路径)。

I need to get the images related to each event 我需要获取与每个事件相关的图像

I have tried the following statement in CakePHP: 我已经在CakePHP中尝试了以下语句:

<?php
   App::uses('AppModel','Model');
   class EventImages extends AppModel {
      public $belongsTo = array('Event' => array('className' => 'Event','foreignKey' => 'eventID'));
 }

but no data is retrieved in the controller any missing statement? 但是没有任何丢失的语句在控制器中检索到的数据?

You have to define relation in Event model 您必须在事件模型中定义关系

 public $hasMany = array('EventImages'=>array('className'=> 'EventImages', 'foreignKey'=>'eventID') //for multiple image

According to naming convention in cakephp Model name should be singular. 根据cakephp中的命名约定,模型名称应为单数。 Also you have to define public $primarykey = 'eventID' in Event model as cakephp by default use id field as primary key. 另外,您必须在事件模型中将public $ primarykey ='eventID'定义为cakephp,默认情况下使用id字段作为主键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM