我有一个有子和父的表,父亲的pid是0,而孩子是父母的id。我想选择那个父母的子女数量的父母。
我的模特:
function parent_child()
{
$row1 =
"SELECT tbl_test.ID,tbl_user.Name,tbl_user.FamilyName,
tbl_test.Name
from tbl_test,tbl_user
WHERE tbl_user.UID=tbl_test.UserID
AND tbl_test.PID=0
AND tbl_test.Status=0
";
$parent=$this->db->query($row1)->result();
foreach ($parent as $row)
{
$row1 =
"SELECT COUNT(ID)
from tbl_test
WHERE tbl_test.PID IN $row->ID ";
$parent['childcount']=$this->db->query($row1)->result();
return $parent;
}
我的控制员:
public function parent_child()
{
$this->load->model('test');
$temp=$this->test->parent_child();
$output= json_encode($temp);
die($output);
}
我想要这个输出
{
"parent": {
"ID": "2",
"childcount": 3
}
}
答案 0 :(得分:1)
试试这个
public function parent_child()
{
$st=$this->db->select('SELECT tbl_test.ID, tbl_test.Name, tbl_user.Name, tbl_user.FamilyName from
tbl_test
JOIN
tbl_user on tbl_user.UID=tbl_test.UserID
WHERE
tbl_test.PID=0 AND
tbl_test.Status=0')->result_array();
if(count($st)>0)
{
for($i=0;$i<count($st);$i++)
{
$rows=$this->db->select('*')->from('tbl_test')->WHERE('PID',$st[$i]['id'])->get()->result_array();
$st[$i]['childcount']=count($rows);
}
return $st;
}
else
{
return array();
}
}
答案 1 :(得分:0)
您可以使用Codeigniter Query Bulider
$this->db->select('tbl_test.ID');
$this->db->from('tbl_test');
$this->db->join('tbl_user', 'tbl_user.PID = tbl_test.ID');
$this->db->where('tbl_test.Status', '0');
$result = $this->db->count_all_results();
return $result;