php - How to properly use models to print an elegant outcome -
i've super new codeigniter 3 , i'm using build task manager (claritask.com). also, i'm starting learn how program, forgive me beforehand if i'm not making sense , i'll try clarify in comments.
as i'm building specific project page lists specifc tasks, curious know if i'm doing right.
what need on view is: tasks belonging specific project & name of project. can work fine, want learn if way of doing correct.
i'm using 2 various methods
the first method i'm using, deals having 2 functions on model, triggering 2 queries:
// show project tasks function get_tasks($project_id) { $this->db->from('tasks'); $this->db->where('tasks.project_id', $project_id); $this->db->order_by('tasks.created_date', 'desc'); return $this->db->get()->result_array(); } // show single project name function get_single_project($project_id) { $this->db->from('projects'); $this->db->where('projects.id', $project_id); return $this->db->get()->row_array(); }
then on controller
$data['tasks'] = $this->project_model->get_tasks($project_id); $data['project_name'] = $this->project_model->get_single_project($project_id)['project_name'];
this working expected, , producing elegant array (especially on projects without tasks).
array ( 'tasks' => array ( ), 'project_name' => 'default name', )
however didn't triggering 2 different queries, decided join projects tasks , have 1 hit database, such:
// show project tasks function get_project_tasks($project_id) { $this->db->select("tasks.*, projects.project_name"); $this->db->from('projects'); $this->db->where('projects.id', $project_id); $this->db->join('tasks', 'tasks.project_id = projects.id', "left"); $this->db->order_by('tasks.created_date', 'desc'); return $this->db->get()->result_array(); }
and controller:
$data['tasks'] = $this->project_model->get_project_tasks($project_id); $data['project_name'] = $data['tasks'][0]['project_name'];
while second approach using 1 query only, it's producing "empty" array (below) on projects without tasks , causing print @ least 1 empty line within 'foreach'.
array ( 'tasks' => array ( 0 => array ( 'id' => null, 'project_id' => null, 'list_id' => null, 'task_text' => null, 'task_due_date' => null, 'created_by' => null, 'created_date' => null, 'project_name' => 'website design', ), ), 'project_name' => 'website design', )
even though, i'm mitigating that, following:
<?php foreach($tasks $task) { ?> <?php if(isset($task['id'])): ?> <div><?php echo $task['task_text']; ?></div> <?php endif; ?> <?php } ?>
even though there thousands of ways skin cat, know approach correct one: having specific query each element , printing elegant output, or optimizing outcome.
wiki
Comments
Post a Comment