Welcome Guest, Not a member yet? Register   Sign In
how can i do this in view
#1

[eluser]mohamedElsnousy[/eluser]
hi all
i have tow table parrent , child
parrent
feilds (id,p_name)
contain (1,parrent1),(2,parrent2),(3,parrent3)

child
feilds (id,c_name,p_id)
contain (1,child11,1),(2,child12,1),(3,child21,2),(4,child22,2) ,(4,child31,3),(5,child32,3)

i need to get this result in view template

parrent1
child11
child12
parrent2
child21
child22
parrent3
child31
child32

what is the best way to get this result ?
#2

[eluser]Unknown[/eluser]
Check out Increasr.com, you can get credits there much faster, you can also get more twitter followers, facebook fans, youtube subscribers and video views. Check it at http://www.increasr.com
#3

[eluser]oppenheimer[/eluser]
You could query the parent table, then use a foreach loop to go through each parent and query the child table for records where the p_id = the current parent in the loop.

If you wanted to get more advanced you could use a DB query with a join where parent.id = child.p_id.

Please post your code if you want more specific help.
#4

[eluser]mohamedElsnousy[/eluser]
dear oppenheimer , thanks for your replay
i understand your idea and it was in my mind
but you now that in CI we can't but DB Query in view
then the quiz is how we can make this two foreach loop in controller
first one for parrent and the second for child

controller

foreach($parrent as $parrent)
{

// what can i write here
}.

view !!!!

foreach()
{
foreach()
{
}
}
#5

[eluser]oppenheimer[/eluser]
Perhaps something like this for your controller:

Code:
foreach($parents as $parent)
{
    $children = $this->Family_model->query_db(array('id'=>$parent['id']),"child");
    echo $parent['p_name'] . "<br />";
    foreach ($children as $child)
          echo " " . $child['c_name'] . "<br />";
}

Your model would be something like this:
Code:
class Family_model extends Model {
    
function Family_model()
{
     // Call the Model constructor
     parent::Model();
}
    
function query_db($where,$table)
{
     $this->db->where($where);
     $query = $this->db->get($table);
     return($query->result_array());
}

//close class
}

If you want to follow the MVC, you should use a "view" for displaying the data so you would need to modify your controller like this (notice the & in the parent foreach which allows us to modify the $parents array inside the foreach loop):
Code:
foreach($parents as &$parent)
{
    $parent['children'] = $this->Family_model->query_db(array('p_id'=>$parent['id']),"child");
}

$data['parents'] = $parents;
$this->load->view('family',$data);

Then the "family" view:
Code:
&lt;?php
foreach ($parents as $parent)
{
     echo $parent['p_name'] . "<br />";
     foreach ($parent['children'] as $child)
          echo $child['c_name'] . "<br />";
}
?&gt;




Theme © iAndrew 2016 - Forum software by © MyBB