如何在codeigniter中创建类别和子类别?

时间:2017-01-11 15:10:22

标签: php twitter-bootstrap codeigniter inner-join parent

我想进行在线图书销售,但我对类别和子类别感到困惑。

所以我决定创建两个表格如下:

表类别

enter image description here

表产品

enter image description here

模型

   <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class Product_model extends CI_Model
    {
        var $table = 'product';

        public function ProductsCategories()
        {
            $this->db->select('*');
            $this->db->from('categories');
            $this->db->join('product', 'product.productID = categories.categoriesID','left');

            $query = $this->db->get();

            $products = array();
            if ($query->num_rows()) 
            {
              foreach ($query->result_array() as $row) 
              {
                $products[$row['categoriesName']][] = $row;
              }
            }
            return $query->result_array();
        }
    }

控制器

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
class Member extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        if ($this->session->userdata('username')=="") {
            redirect('auth');
        }
        $this->load->model('product_model','product');
    }

    public function index()
    {
        $data['username'] = $this->session->userdata('username');
        $data['member'] = $this->product->all();
        $data['categories'] = $this->product->ProductsCategories();
        $this->load->view('member/index', $data);
    }
}

查看

<div class="yamm-content">
    <div class="row">
    <?php foreach($categories as $categoriesName => $row) : ?>
        <div class="col-sm-3">
            <h5><?php echo $categoriesName;?></h5>
            <ul>
            <?php foreach($row as $product) : ?>
                <li><?php echo anchor('method/'.$row['productID'], $row['productName']); ?></a></li>
            <?php endforeach; ?>
            </ul>
        </div>
    <?php endforeach;?>
    </div>
</div>

我想向您展示这样的结果

enter image description here

错误在哪里?感谢

1 个答案:

答案 0 :(得分:0)

您提到模型的方式是错误的:

$data['categories'] = $this->product_model->ProductsCategories();

此外,$ this-&gt; load-&gt;模型需要一个数组。这样:

$this->load->model(array('product_model','product'));