错误的结果Codeigniter查询

时间:2015-09-29 20:13:01

标签: php codeigniter

我是codeigniter和php的新手。这是我的模特:

function getRelated($newsId, $catId){
    $this->db->select('a.id, a.category, a.title, a.photo, a.caption, a. summary, a.detail, a.page_views, b.cat_id');
    $this->db->from('news as a');
    $this->db->order_by("time", "desc");
    $this->db->join('news_categories as b', 'a.id = b.news_id');
    $this->db->where('a.id <>', $newsId);
    $this->db->where('b.cat_id', $catId);
    $query = $this->db->get();
    echo $this->db->last_query();
    return $query->result();
}

这是我的控制者:

public function detail($id, $catId){
        $this->load->model('news_model');
        $data['list'] = $this->news_model->get($id);
        $data['related'] = $this->news_model->getRelated($id, $catId);

        $this->load->view('page_header');           
        $this->load->view('news_detail', $data);            
        $this->load->view('page_footer');
}

这是视图中查询的结果:

  

选择aidacategoryatitlea。{{1} },   photoacaptionasummaryadetaila,   page_viewsb FROM cat_id作为news加入a作为news_categories ON   ba = idb WHERE news_ida&lt;&gt; '2'和idb =   'title%20one%20test1'ORDDER BY cat_id DESC

如上所示(视图),cat_id的结果是标题.. 我的代码怎么了?

我的视图文件(news_detail):

time

帖子的类别是多选。因此,每个帖子都可以有多个类别。我该怎么办?

提前致谢

4 个答案:

答案 0 :(得分:0)

我修改了您的代码。试试这个......!

function getRelated($newsId, $catId){
        $this->db->select('a.id, a.category, a.title, a.photo, a.caption, a. summary, a.detail, a.page_views, b.cat_id');
        $this->db->from('news as a');
        $this->db->order_by("time", "desc");
        $this->db->join('news_categories as b', 'a.id = b.news_id and a.id<>'.$newID.'and b.cat_id=$catID','inner');
        $query = $this->db->get();
        echo $this->db->last_query();
        return $query->result();
}

答案 1 :(得分:0)

你在这里犯了错误

<a class="title" href="news/detail/<?= $value->id . "/" . $value->title ?>"><?= $value->title ?></a>

当您定义任何类似

的功能时
public function detail($id, $catId){ }  

然后$id将是方法名称detail之后的第一个分段,即$value->id$catId将是方法名称之后的第二个分段,即$value->title

所以将catID添加为链接中的第二个段,如下所示     <a class="title" href="news/detail/<?= $value->id . "/" . $value->catID ?>"><?= $value->title ?></a>

答案 2 :(得分:0)

在视图文件(news_detail)中更改锚标记。

此处您发送的是标题而非类别ID

替换

<a class="title" href="news/detail/<?= $value->id . "/" . $value->title?>"><?= $value->title ?></a>

通过

<a class="title" href="news/detail/<?= $value->id . "/" . $value->cat_id?>"><?= $value->title ?></a>

答案 3 :(得分:0)

替换视图文件(news_detail):

<h3>Related News</h3>
<?php
$i = 0;
foreach ($related as $key => $value) {
    if (++$i > 3)
        break;
    ?>
    <div class="list">
        <a class="title" href="news/detail/<?= $value->id . "/" . $value->cat_id ?>"><?= $value->title ?></a>
    </div>
<?php
}?>