This may be chalked up to exhaustion, but I am new to MVC programming and while I have some grasp on it, I am really struggling with a concept. I am working in php/codeigniter on a system that allows a user to post entries and other users are able to vote on them. I have stored the entries in a mysql table entries and the votes in another table votes.
The field that links them together would be entries->id and votes->entryId.
So, in my controller, I have a function that calls the model and gets the recent entries:
$data['recentEntries'] = $this->Entries->getRecentEntries($id);
where $id is the id number of the user’s entries you want to get.
I want to be able to display each entry alongside the corresponding votes for each entry, and normally without MVC I would simply find all the entries for a user, then in a foreach loop, find and display all the votes for each particular entryId.
However, with MVC, the entries are loaded into the variable $data[‘recentEntries’] and I wouldn’t or shouldn’t use the foreach loop to query mysql in the view.
I feel like I am missing a critical mysql or MVC concept here that should take care of this quite simply, so any direction or guiding would be incredibly appreciated.
Many thanks in advance.
— Update —
So I’ve updated the controller so:
$data['recentEntries'] = $this->Entries->getRecentEntries($id);
$data['votes'] = array();
foreach ($data['recentEntries'] as $entry) {
array_push($data['votes'], $this->Votes->getVotes($entry->id));
}
So that $data[‘votes’] now contains the votes for all the entries for a particular user. Is this the right way to go about it? If so, then once in the view’s foreach loop, how do I find and display the appropriate values from this $data[‘votes’] array?
View:
if (count($recentEntries)>0) {
foreach ($recentEntries as $row)
{
echo $row->content;
}
}
You probably to maintain it as a map rather than a simple array so that you maintain the association between an entry and it’s votes. And, yes, I think it’s best to populate the entire model in the controller rather than querying the DB from the view.