Retrieving data from two tables in CodeIgniter

一笑奈何 提交于 2020-01-07 03:08:37

问题


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.


回答1:


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;?>



回答2:


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.)




回答3:


<?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?



来源:https://stackoverflow.com/questions/33929102/retrieving-data-from-two-tables-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!