简体   繁体   中英

Retrieving data from two tables in CodeIgniter

I want to display some categories and their member data like this:

Fruits

  • Orange
  • Grape
  • Apple

Animals

  • Cat
  • Dog
  • Horse

But what I got is something like this:

Fruits

  • Orange

Fruits

  • Grape

Fruits

  • Apple

Animals

  • Cat

Animals

  • Dog

Animals

  • Horse

Here is what I did. In category_model:

function getCategoryMembers(){
   $this->db->join('members','members.category_id=categories.id','left');
   return $this->db->get('categories')->result();
}

In controller, I pass the member and category data.

$data['members'] = $this->category_model->getCategoryMembers();

And, in my view, I write it like this.

<?php foreach ($members as $m) : // list the members ?>
    <?php echo $m->category_name ?>
   <?php echo $m->member_name ?>
<?php endforeach; ?>

Please tell me how to display the data like I want above. I suspect that I have to modify the database query in the model, and also how I loop it, but I'm not sure how. Thanks for your help.

ON join you will get only one row from database, so change your query like this,

SELECT categories.id, GROUP_CONCAT(members.member_name SEPARATOR ', ') as mem
FROM categories 
LEFT JOIN members on members.category_id = categories.id
GROUP BY categories.id

So members will come as comma ( , ) separated values,

Now in view

<?php foreach ($members as $m) : // list the members ?>
     <?php echo $m->category_name ?>
     <?php $a = explode(",",$row->mem);
        foreach($a as $b) {
           echo $b;
        }
     ?>
 <?php endforeach; ?>

Hope this helps.(im not sure about column names, make sure you cross check them and use it.)

I think you need to modify the output of the model. In the controller try this(just modify the columns):

$rec = $this->category_model->getCategoryMembers();
$new_rec = array();
foreach ($rec as $k => $v) {
    $new_rec[$v->category][] = $v->member;
}
$data['members'] = $new_rec;

And for the view :

<?foreach ($members as $k => $v):?>
  <h3><?php echo $k ?></h3>
    <?if($v):?>
        <?foreach ($v as $m):?>
            <p><?=$m?></p>
        <?endforeach;?>
    <?endif;?>
<?endforeach;?>
<?php foreach ($members as $m) : // list the members ?>
     <?php echo $m->category_name; ?>
     <?php foreach ($m->member_name as $n) : // list the names ?>
         <?php echo $n; ?>
     <?php endforeach; ?>
<?php endforeach; ?>

Something like this?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM