简体   繁体   中英

Looping through associated data in CakePHP

I am feeling my way through CakePHP, trying to replicate what I can already do in vanilla PHP.

I have 2 tables, events and eventlist . events contains general information about an event. eventlist contains information that appears as a bullet-pointed list on each event page.

eventlist consists of an id, an event_id which links each entry to the relevant event in the event table, and a string that is displayed on the page. In vanilla PHP, I would simply SELECT list_info FROM eventlist WHERE event_id = 1 or whatever, and loop through the resulting array.

However, I have no idea where to start with this in CakePHP, and I'm not sure how i'd search for it to find out.

I have already created an association between the two tables:

class Event extends AppModel{

    public $hasMany = array(
        'EventList'
        );

}

class EventList extends AppModel{

public $useTable = 'eventlist';

public $belongsTo = array(
    'Event'
);

}

And I have a simple view set up for Event :

<h2><?php echo $event['Event']['event_name'] ?></h2>

<p><?php echo $event['Event']['event_description']?></p>

<h3>£<?php echo $event['Event']['event_cost']?></p>

But now I have no idea what to do - I am new to CakePHP and MVC as a whole. I assume I need to do something in EventListController to load the data into an array. Any help appreciated.

By default, the relationships that you have setup should return the associated data when you query for an event. There are a number of ways to get the data in a displayable format, such as using HTML helper to output an (un)ordered list. But, the example below should help.

Also, a quick way to debug the results from finding a record in your controller is to use pr (an alias for print_r) like pr($event);exit; . There are other ways to debug too, but this is a quick and dirty method if you're working locally.

Controller

$event = $this->Event->findById(`event_id`);
$this->set(compact('event'));

View

<h2><?php echo $event['Event']['event_name'] ?></h2>
<p><?php echo $event['Event']['event_description']?></p>
<p>£<?php echo $event['Event']['event_cost']?></p>
<!-- Output each list item in a paragraph -->
<p>
    <?php foreach($event['EventList'] as $listItem:
       echo $listItem['ListItemColumn'];
    endforeach; ?>
</p>

Again...many many ways to get and output this data, but the long and short is that the returned results should have an array key Event and an array key EventList with the data from each table stored within those keys.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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