在我的项目中,我将类别和子类别记录保存在同一个表中,tbl_categories
如果parent_cat_id是'0',那么它的主要类别parent_cat_id将包含主类别的cat_id。
我想列出带有以下字段的子类别:
- 1(类别编号(子类别(
- 2( 类别名称
- 3(子类别名称。
我无法实现上述查询
SELECT cat_name
FROM `tbl_categories`
WHERE cat_id IN (
SELECT parent_cat_id FROM `tbl_categories`
) <-this is what i implemented in phpmyadmin
我想在编码器中实现它
试试这个:
$sql = "select t1.name as category_name, t2.name as parent_cat_name
from tbl_categories as t1
left outer join
tbl_categories as t2
on t2.id = t1.parent_cat_id";
$query = $this->db->query($sql)->result_array();
return $query;
参考 NIPUN SARKER @M答案,查询也可以写成 -
$this->db->select('t1.name as category_name, t2.name as parent_cat_name'); // select what you might want to select
$this->db->from('tbl_categories t1');
$this->db->join('tbl_categories t2', 't2.id = t1.parent_cat_id', 'left');
$query = $this->db->get()->result();
return $query;
它将在category_name
中生成类别,并在parent_cat_name
中生成其父类别,您可以通过其中访问
// suppose $your_variable contains the result generated through query
foreach($your_variable as $variable){
echo 'Category Name: '.$variable->category_name.' Parent Category Name: '.$variable->category_name.'<br>';
}
看看这是否对您有帮助。