猿问

使用 foreach 循环时限制查询在 codeigniter 中不起作用

我正在尝试使用以下查询限制 foreach 循环中的分页结果,但我没有限制我使用以下查询获得所有结果。


public function get_tags($limit, $start, $tag_id)

{    

    $snippetstagdata = $this->getDataOneColumn("snippets_tags","tag_id",$tag_id);

    foreach ($snippetstagdata as $getSnippet) {

        $snippet_id = $getSnippet->snippet_id;

        $this->db->where("id", $snippet_id);

        $this->db->select('*');

        $this->db->from('snippets');

        $this->db->limit($limit, $start);

        $query = $this->db->get();

        $result[] = $query->result();


    }


    $this->db->save_queries = false;


    return $result;

}

然而 getDataOneColumn


public function getDataOneColumn($table, $col1_name, $col1_value)

{

    $this->db->where("$col1_name", $col1_value);

    $query = $this->db->get("$table");

    $result = $query->result();

    $this->db->save_queries = false;


    return $result;

}

更新


肥皂起泡泡
浏览 170回答 2
2回答

扬帆大鱼

您在 foreach 循环的帮助下查询数据库的方法是错误的。正确的方法是在查询中使用连接:从您的函数getDataOneColumn()中,您仅使用snippet_id 值,您可以使用它来创建连接:public function getDataOneColumn($table, $col1_name, $col1_value, $limit, $start){    $this->db->select("t1.*,t2.*")             ->where("t1.$col1_name", $col1_value)             ->join("snippets t2","t1.snippet_id=t2.id")             ->limit($limit, $start);    $query = $this->db->get("$table t1");    $result = $query->result();    return $result;}注意:在您的示例$tag_id=$col1_value中,请使用更适合的任何变量名称。那么你的第二个功能get_tags()就完全没有必要了。

慕尼黑的夜晚无繁华

我希望这能帮到您public function get_tags($params = array(), $tag_id){   $result = array();    $snippetstagdata = $this->getDataOneColumn("snippets_tags","tag_id",$tag_id);    foreach ($snippetstagdata as $data) {                $this->db->where('id',$data['snippet_id']);        if(isset($params) && !empty($params))        {            $this->db->limit($params['limit'], $params['offset']);        }        $result[$data['snippet_id']] = $this->db->get('snippets')->result_array();    }    return $result;}和public function getDataOneColumn($table, $col1_name, $col1_value){    return $this->db->get_where($table,array($col1_name=>$col1_value))->result_array();}
随时随地看视频慕课网APP
我要回答