CodeIgniter中Products与Products_images表:单模型还是双模型更优?
在CodeIgniter中处理关联表的模型设计建议
这得根据你的项目复杂度、代码复用需求来决定,两种方案各有优劣,我给你详细拆解下:
方案一:创建两个独立模型(推荐大多数场景)
这种方式符合单一职责原则,每个模型只负责对应数据表的操作,代码结构更清晰,后续维护和扩展也更方便——比如以后你需要单独操作商品图片(比如批量删除某类商品的图片),直接调用图片模型的方法就行,不用去改商品模型的代码。
举个简单的示例:
Products_model.php
class Products_model extends CI_Model { public function get_product($id) { return $this->db->get_where('Products', ['id' => $id])->row(); } // 其他商品相关操作:新增、更新、删除等 }
Products_images_model.php
class Products_images_model extends CI_Model { public function get_images_by_product_id($product_id) { return $this->db->get_where('Products_images', ['id_product' => $product_id])->result(); } // 其他图片相关操作:新增图片、删除图片等 }
在控制器里调用的时候,你可以同时加载两个模型,组合数据:
$this->load->model('Products_model'); $this->load->model('Products_images_model'); $product = $this->Products_model->get_product(1); $product->images = $this->Products_images_model->get_images_by_product_id($product->id);
方案二:用一个模型(适合简单场景)
如果你的项目里,商品和图片的操作永远绑定在一起——比如从来不会单独操作图片表,只会在获取商品时同时拿图片,新增商品时同时上传图片,那可以把所有逻辑放在一个Products_model里,减少文件数量。
示例代码:
class Products_model extends CI_Model { public function get_product_with_images($id) { // 先获取商品信息 $product = $this->db->get_where('Products', ['id' => $id])->row(); if ($product) { // 关联获取对应的图片 $product->images = $this->db->get_where('Products_images', ['id_product' => $id])->result(); } return $product; } // 新增商品同时添加图片的方法 public function add_product_with_images($product_data, $images_data) { $this->db->trans_start(); $this->db->insert('Products', $product_data); $product_id = $this->db->insert_id(); // 给每个图片数据添加上商品ID foreach ($images_data as &$image) { $image['id_product'] = $product_id; } $this->db->insert_batch('Products_images', $images_data); $this->db->trans_complete(); return $this->db->trans_status(); } }
总结
- 如果项目有一定规模,或者以后可能需要单独操作图片表,优先选两个独立模型,代码更健壮、易维护;
- 如果是小型项目,且商品和图片的操作完全绑定,用一个模型也能简化结构。
内容的提问来源于stack exchange,提问作者Hernán Gabriel
相关产品推荐
相关产品推荐

