doushen8391 2011-10-03 11:50
浏览 48
已采纳

如何在Codeigniter中编写类别/子类别数据库查询(一级深度)?

Ah, the aged old question of parent / child categories in PHP. My apologies if this question has been asked already (I know it has in many forms), but doing a search couldn't specifically answer how to do this using one query and Codeigniter.

Basically I am developing a classifieds website using Codeigniter. A listing can be assigned to a category. A category can be stand-alone (no children) or a category can have one child.

Using Codeigniter's "Active Record" functions, I have the following that almost works.

$this->db->select('l.*');
$this->db->select('c.cat_parent, c.cat_slug, c.cat_name, c.cat_description, c.cat_display');
$this->db->select('c2.cat_slug AS parent_cat_slug, c2.cat_name AS parent_cat_name, c2.cat_description AS parent_cat_description, c2.cat_display AS parent_cat_display');

$this->db->limit($limit, $offset);

$this->db->join('listing_status ls', 'ls.status_id = l.listing_status');
$this->db->join('categories c', 'c.cat_id = l.listing_category');
$this->db->join('categories c2', 'c2.cat_parent = c.cat_id');

return $this->db->get('listings l')->result();

I want to be able to pull out a listing, it's assigned category and if that category the listing belongs to has a parent, get the parent category details as well. I've added in 2 joins and it should be working, is there something I've missed?

  • 写回答

1条回答 默认 最新

  • duanfei9278 2011-10-03 11:58
    关注

    After a little messing around, I realised that my second join was wrong. Here is my updated and working code in hopes it helps someone else.

    $this->db->select('l.*');
    $this->db->select('c.cat_parent, c.cat_slug, c.cat_name, c.cat_description, c.cat_display');
    $this->db->select('pc.cat_slug AS parent_cat_slug, pc.cat_name AS parent_cat_name, pc.cat_description AS parent_cat_description, pc.cat_display AS parent_cat_display');
    
    $this->db->limit($limit, $offset);
    
    $this->db->join('listing_status ls', 'ls.status_id = l.listing_status');
    $this->db->join('categories c', 'c.cat_id = l.listing_category');
    $this->db->join('categories pc', 'pc.cat_id = c.cat_parent');
    
    return $this->db->get('listings l')->result();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探