如何使用foreach循环到另一个foreach循环来遍历c​​odeigniter中的两个不同的数据表?

时间:2017-01-23 13:04:21

标签: php mysql codeigniter foreach

是否可以在foreach循环中使用foreach循环遍历两个不同的数据库表以获得结果?

我想显示admin_1为其用户和客户插入的产品列表? 我将产品和用户分为两个不同的表格。我正在使用admin_id来区分产品和用户。 但我没有得到如何获得确切结果。 任何帮助表示赞赏。

这是我的代码:

<?php if (!empty($products)) { ?>
                    <?php foreach ($products as $product) { ?>

                        <?php if((($this->session->userdata('user_id')) == ($product->id_admin)) || (userdata('department') == 0 )) { ?>

1 个答案:

答案 0 :(得分:1)

如果要组合两个不同表的结果,解决方案始终使用 UNION 。见https://dev.mysql.com/doc/refman/5.7/en/union.html

以下是一个简单的UNION示例:

<?php

public function retrieve_products_users_by_username($this_user) { // place this function into your model
    $this->db->where('username',$this_user);
    $this->db->select('id');
    $this->db->limit(1);
    $query_for_this_user = $this->db->get('users'); // whatever table you store the admin_1
    $this_user_id = $query_for_this_user->row_array()['id'];

    $this->db->select('products.id_admin as id_admin ,products.title as column1, products.icon as column2, products.descrption as column3 ...');
    $this->db->from('products');
    $products_query = $this->db->get_compiled_select();

    $this->db->select('users.id_admin as id_admin ,users.username as column1, users.profile_picture as column2, users.address as column3 ...');
    $this->db->from('users');
    $users_query = $this->db->get_compiled_select();

    $query = $this->db->query('SELECT * FROM (' . $products_query . ' UNION ' . $users_query . ') AS u WHERE u.id_admin='.$this_user_id);
    return $query->result_array();
}

?>

我使用您在问题和评论中提供的有限信息编写此功能。根据您的表格列名等,它在现实中可能会略有不同。

无论如何,当您在模型中完全准备好此功能时,您可以从控制器中调用它,如下所示:

<?php

$this->data['results'] = $this->YOURMODELNAME_model->retrieve_products_users_by_username('admin_1');

?>

正如我所说 UNION 是您的解决方案。 加入不是您的解决方案,因为:

  • 加入只需简单地连接两个表水平
  • UNION 简单地连接两个表垂直