[英]Codeigniter 3: inner join results in ambiguous variable name to be used in the view
我正在Codeigniter 3.1.8和Bootstrap 4中開發一個基本的博客應用程序 。
有幾個表,其中的posts
和categories
存儲職位類別。
每個帖子都屬於一個類別:
類別名稱:
我想顯示帶有每個帖子所屬類別的名稱的帖子。 為此,在我的帖子模型中,我有以下代碼:
public function get_posts($limit, $offset) {
$this->db->order_by('posts.id', 'DESC');
$this->db->join('categories', 'posts.cat_id = categories.id', 'inner');
$query = $this->db->get('posts', $limit, $offset);
return $query->result();
}
上面的代碼在
`SELECT * FROM `posts` INNER JOIN `categories` ON `posts`.`cat_id` = `categories`.`id` ORDER BY `id` DESC LIMIT 12`
並且,如果我執行print_r($data['posts'])
它會模糊地將帖子類別名稱返回為[name] => Showbiz
。
這迫使我在帖子視圖中使用以下歧義行:
<p><?php echo $post->name; ?></p>
我希望能夠改用此行:
<p><?php echo $post->post_category; ?></p>
換句話說,我要使用Codeigniter 3語法:
`SELECT *, categories.`name` as post_category FROM `posts` INNER JOIN `categories` ON `posts`.`cat_id` = `categories`.`id` ORDER BY `id` DESC LIMIT 12`;
並且仍然能夠使用Codeigniter的ORM功能。
注意:在控制器中,我有:
$data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);
我想念什么?
$this->db->select('posts.*, categories.*');
$this->db->from('posts');
$this->db->join('categories','posts.cat_id= categories.id','INNER');
$this->db->where('posts.id',2);
$res = $this->db->get();
附加select
和使用別名as
該類別列名聲明,如下圖所示。 因此,現在您將能夠echo $post->post_category;
<?php
public function get_posts($limit, $offset) {
$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('posts', $limit, $offset);
return $query->result();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.