在一次查询中选择所有项目和相关项目


select all items and related items in one query

我正在使用最新的codeigniter

我正试图从数据库中获取所有产品和每个产品的所有相关项目。有一段时间没有编码,所以我被困在输出..

这是我的模型:

   public function collections() {
        $this->db->select('*');
        $this->db->from('products');
        $this->db->join('product_images', 'product_images.from_set = products.img_set_ref');
        $this->db->order_by('products.id');
        $q = $this->db->get();         
        if ($q->num_rows() > 0) {       
            return $q->result();        
        }
        return false;               
    }

控制器:

    public function products() {   
    $this->load->model('Frontend'); 
    $page_data['results'] = $this->Frontend->collections();       
    $this->load->view('collections', $page_data);           
}

这是我想要得到的输出(两个产品的例子):

            <div class="pr"> //product 1
            <a href="img/pr_1.jpg" rel="gallery01"><img src="img/pr.jpg" alt="">
            </a>
            <a href="img/pr_2.jpg" rel="gallery01"><img src="img/pr.jpg" alt="">
            </a>
        </div>
        <div class="pr"> //product two
            <a href="img/pr_12.jpg" class="fancybox" rel="gallery02"><img src="img/pr.jpg" alt="">
            </a>
            <a href="img/pr_22.jpg" class="fancybox" rel="gallery02"><img src="img/pr.jpg" alt="">
            </a>
        </div>

我不知道如何在视图中的foreach循环中正确地返回产品,以便它们在上面的结构中。如何做到这一点?

如果我需要一种又快又脏的方法,我会选择为每个产品构建一个临时的图像数组

$groupedProducts = array();
foreach ($products as $product) {
     if (!array_key_exists($product['id'], $groupedProducts) {
         $groupedProducts[$product['id']] = $product;
         $groupedProducts[$product['id']]['images'] = array();
     }
     $groupedProducts[$product['id']]['images'][] = $product['product_images.url'];
}
然后

迭代
foreach ($groupedProducts as $product) {
    // output some description, title, price, etc.
    foreach ($product['images'] as $imageUrl) {
        echo '<img src="'.$imageUrl.'">';
    }
}

我可以看到你的控制器,这样我就可以看到你的数据将如何查看。在控制器:

$result[image] = $this->your modelname->model function()

像这样传递图像数组给view:

$this->load-view(your view name,$result)

In view:像这样放置foreach:

foreach ($image as images):
    $variablename = $images['column name'];
Echo $variable;
endforeach;

列名称是您要获取的数据库列名称

要么在collections函数中使用两个查询,要么编写第二个函数来获取产品。

在新函数中获取这些产品并将它们作为参数传递给集合函数。在集合函数中,你可以使用IN语句编写查询,或者执行foreach循环,每次查询数据库,并以你喜欢的方式构建数组。

使用in语句,你可以像这样:

"WHERE your_field IN ("'.implode('", "', $products) . "')"

,然后遍历结果并匹配字段并构建数组。

使用foreach

foreach($products as $key => $product){
      $myarray[] = .... write your query and get the result
}