简体   繁体   English

Codeigniter从概述中的其他表获取名称

[英]Codeigniter get name from other table in overview

Im getting a list from my database with the following (in my controller): 我从数据库中获取以下内容的列表(在我的控制器中):

$view["interactions"] = $this->interacties->getInteractionsId($id);

This gives an array with everything in my database in the table 'interactions'. 这给出了一个数组,其中包含“交互”表中数据库中的所有内容。

Im posting this to my view with the following foreach loop: 我通过以下foreach循环将其发布到我的视图中:

<?php if($interactions): ?>
   <?php foreach($interactions as $interaction): ?>
      <tr class="gradeX">
         <td><a href="<?=site_url('interactie/single/'.$interaction['id'])?>"><?=$interaction['datum']?></a></td>
         <td><?=$interaction['gebruikers_id']?></td>
         <td><?=$interaction['gesproken_met']?></td>
         <td><?=$interaction['interactie']?></td>
      </tr>
   <?php endforeach; ?>
<?php else: ?>
   <p>Geen interacties</p>
<?php endif; ?>

This works fine, but now I want to change the $interaction['gebruikers_id'] to a name which is in my 'users' table which is called 'naam'. 这可以正常工作,但是现在我想将$interaction['gebruikers_id']更改为我的“用户”表中的名称,即“ naam”。 Normaly I would get the id and use another get function. 通常,我会获取ID并使用另一个get函数。 But because this is in a foreach loop I'm not sure how to do this. 但是因为这是在foreach循环中,所以我不确定如何执行此操作。

This is the function in the Model: 这是模型中的功能:

public function getInteractionsId($id) {
    $this->db->select('*');
    $this->db->where('bedrijf_id', $id);
    $query = $this->db->get('interacties');

    return $query->num_rows() > 0 ? $query-> result_array() : FALSE;

}

If you change your model function to this: 如果将模型函数更改为:

public function getInteractionsId($id) {
  $this->db->select('interacties.*, gebruikers.naam');
  $this->db->join('gebruikers', 'interacties.gebruikers_id = gebruikers.id');
  $this->db->where('bedrijf_id', $id);
  $query = $this->db->get('interacties');
  return $query->num_rows() > 0 ? $query-> result_array() : FALSE;
}

You can do this in your view: 您可以在自己的视图中执行此操作:

<?=$interaction['naam']?>

If you are not familiar with the basics of database joins, check out this article . 如果您不熟悉数据库连接的基础知识,请参阅本文

Since you are in a view, you should only do presentation stuff, no further database calls. 由于您处于视图中,因此您仅应执行演示文稿内容,而无需进行其他数据库调用。

You could do this in the controller in an extra foreach loop. 您可以在控制器中的额外foreach循环中执行此操作。

Still, the best option IMHO is to patch your method getInteractionsId() to join with users table so that you will have both $interaction['gebruikers_id'] and $interaction['users_naam']. 不过,最好的恕我直言,最好的方法是修补方法getInteractionsId()以与users表联接,以便同时拥有$ interaction ['gebruikers_id']和$ interaction ['users_naam']。

Whatever you end up to, think of fat models and skinny controllers . 无论您做什么,都可以考虑胖模型和瘦控制器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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