I'm developing a small module on CakePHP 3 and I'm currently encountering a small problem that I can't seem to solve.
I have two tables: Events and shop_ticket.
Events table:
I store information related to the event (id, name, description).
Shop_ticket table:
I record the elements related to the event when the ticket is purchased (user_id, event_id).
My problem is that when I try to retrieve the event-related information on my "ticket history" page, it systematically retrieves the last item for each user. I haven't found a solution to this problem yet. Does anyone have any suggestions?
Below is the latest code I've tested.
I've been trying to find a solution for several days now, and everything I've tried gives me the same result.
$ticketTable = TableRegistry::getTableLocator()->get('ShopTicket');
$ticket = $ticketTable->find('all', [
'conditions' => ['ShopTicket.user_id' => $this->request->getSession()->read('Auth.User.id')]
]);
foreach ($ticket as $item) {
$eventTable = TableRegistry::getTableLocator()->get('Events');
$event = $eventTable->find('all', [
'conditions' => ['Events.id' => $item->event_id]
]);
$this->set('event_info', $event);
}
$this->set('ticketList', $ticket);
event_infoinside aforeachloop, so only the very last such result will still be available when you get to your view. This is not a Cake issue, it's just how PHP works. You can't have two things with the same variable name. If your application is configured properly, with associations between the tables, you'd be able to just add'contain' => 'Events'after the conditions on the$ticketTablefind call, and the events will all be available in your view under$ticket->eventsto iterate over.