CodeIgniter中的一对多数据库关系

3

我有一些产品和一些图片。还有更多的图片,它们有一个p_id。如何获取多个图片?这是为了制作图库。

我的当前查询:

    $this->db->select('prod_id, prod_name, prod_link, prod_description, prod_status, prod_price, brand_link, link, cat_link, normal, thumbnail');

    $this->db->from('product');
    $this->db->join('category', 'cat_id = prod_category');
    $this->db->join('brands', 'brand_id = prod_brand');
    $this->db->join('images', 'p_id = prod_id');

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

    return $query->row_array();

这只给了我第一张图片和剩下的信息。如果我将其更改为result_array(),它会给我第二个数组中的另一张图片(以及来自产品的其他结果,这是没有意义的)。

据我所知,使用Codeigniters活动记录库没有办法做到这一点,除非使用$this->db->query("SELECT ... ");编写所需的SQL语句。您可以再次访问数据库,为每个产品获取一个图像数组。 - Jeemusu
是的,我删除了我的答案,因为我没有正确阅读问题,我以为你是从图像表中进行选择。 - Rick Calder
没错。我真正想要的是一个产品数组中带有图片的数组。 - user1454771
1个回答

6

如我上面所提到的,你可以再次访问数据库获取该产品的图像数组,然后将这些结果添加回原始查询数组中。

$this->db->select('prod_id, prod_name, prod_link, prod_description, prod_status, prod_price, brand_link, link, cat_link, normal');
$this->db->join('category', 'cat_id = prod_category');
$this->db->join('brands', 'brand_id = prod_brand');
$query = $this->db->get('product')->result_array();

// Loop through the products array
foreach($query as $i=>$product) {

   // Get an array of products images
   // Assuming 'p_id' is the foreign_key in the images table
   $this->db->where('p_id', $product['prod_id']);
   $images_query = $this->db->get('images')->result_array();

   // Add the images array to the array entry for this product
   $query[$i]['images'] = images_query;

}
return $query;

谢谢!稍作修改后,这个完美地运行了! - user1454771
这就是我正在寻找的。谢谢! - Sahan Pasindu Nirmal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接