【问题标题】:One-to-many DB relationship in CodeIgniterCodeIgniter 中的一对多数据库关系
【发布时间】:2012-11-20 09:57:32
【问题描述】:

我有一些产品和一些图片。还有更多图像,它们有一个 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 语句。您可以再次访问数据库以获取每个产品的图像数组。
  • 是的,删除了我的答案我没有正确阅读问题,我以为您是从图像表中选择的。
  • 没错。我真正想要的是我的产品数组中包含图像的数组。

标签: database codeigniter relationship


【解决方案1】:

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

$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;

【讨论】:

  • 谢谢!!稍作修改即可完美运行!
  • 这就是我要找的。交易
猜你喜欢
  • 1970-01-01
  • 2011-07-30
  • 1970-01-01
  • 2014-08-18
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多