【问题标题】:->result() not showing all data/rows->result() 不显示所有数据/行
【发布时间】:2019-11-19 14:30:57
【问题描述】:

我有一个问题

假设我们的数据库中有这 2 个表

第一个表:category_lists

第二个表:data_category

所以 如果 list_data_id 等于 1 意味着它有 2 个数据 如果你查看 data_category 表 这是 6 和 7

现在我想要的是从 category_list 表中查询,以便 67 将回显 Car Wreckers汽车现金

这是我的代码的样子:

下面是我的控制器:

 public function index($listing_name)
{
    $this->load->view('layouts/head_layout_seo');
    $this->load->view('layouts/head_layout');

    $data['main_view'] = 'listings/main_view';
    $data['listing_data'] = $this->Listing_model->get_detail_listing($listing_name);

    $list_id = $data['listing_data']->list_data_id; // this is what I get list_data_id is equal to 1

    $data['category_ads'] = $this->Ads_model->get_ads($list_id); // this is what you need to look

    $this->load->view('layouts/main', $data);

    $this->load->view('layouts/footer_layout');

} 

下面是我的模型:

  public function get_ads($list_id)
{
    $this->db->where('list_data_id', $list_id);
    $query = $this->db->get('data_category');
    $query = $query->result();
    //return $query;
    if (count($query) > 0) {    
        for ($i=0; $i < count($query); $i++) { 
            foreach ($query as $value) {
                $this->db->where('category_lists_id', $value->category_lists_id);
                $querys = $this->db->get('category_lists');
                //print_r($query);
                return $querys->result();
            }
        }    
    }
} 

以下是我的看法:

 foreach ($category_ads as $value) {
<p><a href=""><?php echo $value->categories; ?></a></p>  }

使用上面的代码,我只得到 1 个数据,正如您从表格中看到的那样,它是 Car Wreckers,它应该显示 2 个数据 > Car WreckersCash For Cars

谁能帮我解决这个问题?

谢谢

【问题讨论】:

  • 我不熟悉 Codeigniter,但是通过查看您的逻辑,您的 foreach 循环仅在您返回值之后遍历第一个元素,它永远不会到达数组的末尾。跨度>
  • 还有一个嵌套循环,如果data_category 表中有多个结果,它将多次打印结果。
  • 为什么不在模型查询中使用join
  • $query = $query->result_array();
  • @catcon 如果我放置该行 return $querys->result();在 foreach 循环的右括号之后,我将获得 Cash For Cars 而不是 Car Wreckers。

标签: php sql codeigniter


【解决方案1】:

在你的模型中试试这个,这样就不需要两次调用DB,也不需要loop

public function get_ads($list_id)
{
   $this->db->select('cl.category_lists_id,cl.categories');
   $this->db->from('category_lists cl');
   $this->db->join('data_category dc','cl.category_lists_id = dc.category_lists_id');
   $this->db->where('dc.list_data_id',$list_id);
   $query = $this->db->get();
   if($query->num_rows() > 0){
       return $query->result();
   }else{
       return array();
   }
}

【讨论】:

  • 非常感谢,过去两天我一直在寻找这个答案
猜你喜欢
  • 2020-11-07
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 2017-06-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 2014-03-30
相关资源
最近更新 更多