简体   繁体   中英

Codeigniter 3: where clause gives an ambiguous column error

I am working on a basic blog application in Codeigniter 3.1.8 and Bootstrap 4.

There are several tables, among which authors , posts and categories which stores the posts categories.

I am displaying the posts with the name of the category each post belongs to.

I also want to display post filtered by author. In other words, all posts written by an author . For this purpose I have created a method in the Posts_model model:

public function get_posts_by_author($author_id) {
    $this->db->select('posts.*,categories.name as post_category');
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'posts.cat_id = categories.id', 'inner');
    $query = $this->db->get_where('posts', array('author_id' => $author_id));
    return $query->result();
}

In the Posts controller, I have the method:

public function byauthor($author_id){
    $data = $this->Static_model->get_static_data();
    $data['pages'] = $this->Pages_model->get_pages();
    $data['categories'] = $this->Categories_model->get_categories(); 
    $data['posts'] = $this->Posts_model->get_posts_by_author($author_id);
    echo  $author_id;
}

At /posts/byauthor/1 , instead of "1", the author's id, as it was intended, I see Column 'author_id' in where clause is ambiguous .

Where is my mistake?

Solved the problem by changing the method in the model to:

public function get_posts_by_author($authorid) {
    $this->db->select('posts.*,categories.name as post_category');
    $this->db->order_by('posts.id', 'DESC');
    $this->db->join('categories', 'posts.cat_id = categories.id', 'inner');
    // the line below was changed
   $query = $this->db->get_where('posts', array('posts.author_id' => $authorid));
    return $query->result();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM