[eluser]Vheissu[/eluser]
I am currently developing a classifieds system using Codeigniter and plan it being my first finished Codeigniter web project, but that is for another day. When displaying a listing I want to display the category it belongs to and if the category has a parent, then display the name of that category.
I have a solution that works at present (although it feels a bit dirty), I was wondering if anyone can come up with an awesome working solution to help me out? I've posted my code below.
My listings model with a function that returns active listings:
Code:
public function fetch_all_active()
{
return
$this->db
->group_by('listings.listing_name')
->from('listings, categories, usermeta')
->where('listings.listing_status', '1')
->join('categories c', 'c.category_id = listings.listing_category_id')
->join('usermeta u', 'u.meta_user_id = listings.listing_owner_id', 'left')
->get()
->result_array();
}
My listings controller:
Code:
public function index()
{
$data['CI'] = & get_instance();
$data['listings'] = $this->mlisting->fetch_all_active();
$this->parser->parse('listings.php', $data);
}
My listings view (using Dwoo for templating):
Code:
{foreach $listings listing}
<p><strong>Listing name</strong>: {$listing.listing_name}</p>
<p><strong>Description</strong>: {$listing.listing_description}</p>
{$cat1 = $CI->mcategories->get_category($listing.category_parent)}
<p><strong>Category</strong>: {$cat1.category_name} -> {$listing.category_name}</p>
<p><strong>Owner</strong>: {$listing.first_name} {$listing.last_name}</p>
<div><strong>Content:</strong> {$listing.listing_content}</div>
<hr />
{/foreach}
As you can see I am storing the Codeigniter instance inside of a variable and then I am calling another model which has a function that will get me the category name if it is supplied a category ID.
See below for the function that fetches a category name via an ID:
This is a model called, 'mcategories'
Code:
function get_category($id){
$data = array();
$Q = $this->db
->select('category_name')
->from('categories')
->where('category_id', $id)
->get();
if ($Q->num_rows() > 0){
$data = $Q->row_array();
}
$Q->free_result();
return $data;
}
Is there a better way that I can do this? I hate having to pass the Codeigniter instance to my view and then call a model function. I also would prefer to keep that function in it's mcategories.php file because I am trying to keep relevant code inside of relevant model files.