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

时间:2016-03-07 20:56:19

标签: php mysql codeigniter

使用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';

我正在尝试像这样的codeigniter

  $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是1的孩子

1 个答案:

答案 0 :(得分:1)

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

$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;

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

相关问题