SQL 结果来自一个表匹配另一个表(包括子字段)的字段


sql results from a table matching field from another table including sub fields

使用codeigniter查询,我无法获得适当的结果我需要以这种方式获取表格的结果

$catid=$_POST['category'];
$new_id = select catid from categories_table where catid='$catid' and parent='$catid';

所以它还将添加包括其他猫作为父母$cadid的结果

Select * from articles_table where catid = '$new_id';

我正在像这样尝试编码点火器

  $p=$this->input->post('category');
  $this->db->select('catid');
  $this->db->where('parent',$p);
  $this->db->where('catid',$p);
  $query = $this->db->get('categories_table');
  if($query->num_rows()>0)
             {
             foreach($query->result() as $row)
             $new_id[]=$row->catid;
             }
  $this->db->where('catid',$new_id);
  $this->db->where('status',1);
  $this->db->order_by('time_added', 'desc');  
  $res = $this->db->get('articles_table');
  $query_res= $res->result();

它给出了错误Message: Trying to get property of non-object

cats table
catid -- parent -- name
1      -- 0          -- first cat
2  --     1         -- cat child of first
Article table
id -- catid - content
1  -- 2     -- first article
2 --  1     -- second article

如果我查询 cat id = 1 的位置,它也应该返回 catid 2 的结果,因为 2 是一个的孩子

我会尝试使用这样的模型:

$p = $this->input->post('category');
$query = $this->db
    ->select('catid')
    ->where('parent',$p)
    ->or_where('catid',$p)
    ->get('categories_table');
$data = array();
if($query->num_rows())
{
   foreach($query->result() as $row)
   {
       $res = $this->db
            ->where('catid',$row->catid)
            ->where('status',1)
            ->order_by('time_added', 'desc') 
            ->get('articles_table');
       foreach ($res->result() as $article_data)
       {
          $data[] = $article_data;
       }
    }
}
return $data;

代码首先检查$p等于catid或categories_table中parent的类别。然后检查与类别具有相同catid的文章,并将所有文章添加到数组中,$data .