문제

I want to get category name for news post. I can easily get category id but I want to get category name using category Id or other method. How should I do that?

This is how I displayed my blog post in controller

function post($slug = FALSE)
{
    if (isset($slug)) {
        $data['query'] = $this->mdl_blogs->get_where_slug($slug);

        $data['view_file'] = "blog_view";
        $this->load->module('template');
        $this->template->public_one_col($data);
    }



}

in model

function get_where_slug($slug){
 $table = $this->get_table();
$this->db->where('news_slug', $slug);
$query=$this->db->get($table);
return $query;
}
 in view
 <?php
                foreach ($query->result() as $row) {

                $data['news_title'] = $row->news_title;
                $news_body = $row->news_body;
                $news_slug = $row->news_slug;
                $category_id = $row->category_id;


                //$data['category_name'] = $row->category_name;
                //$news_category = $row->news_category;
                    ?>

<h2><a href="<?php echo   (base_url().'blogs/post/'.$news_slug) ;?>">
 <?php echo $data['news_title'];?></a></h2>
                <p><?php echo $news_body;?></p>
                <p><?php echo $category_id;?></p>



                                    <?php
                    }
                    ?>
                    <?php
                        //echo Modules::run('comments');
                    ?>

Here I also want to display category name. I want to get it from categories table

Here are my tables

in News table 
news_id
category_id
news_slug
......

in categories 
category_id
category_name
category_slug
도움이 되었습니까?

해결책

You need to join your category table in your model

function get_where_slug($slug){
$table = $this->get_table();
$query=$this->db
            ->select('n.*,c.category_name,c.category_slug')
            ->from($table.' n')
            ->join('category c','n.category_id=c.category_id','LEFT')
            ->where('n.news_slug', $slug)
            ->get();
return $query;
}

And in your view you can have you category name in foreach loop as

$category_name = $row->category_name;

same for category_slugif you want this too

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top