gpt4 book ai didi

php - 代码点火器。从数据库中获取3个表中的值(多对多)

转载 作者:行者123 更新时间:2023-11-30 00:26:51 25 4
gpt4 key购买 nike

对不起我的英语:)

我是Codeigniter的新手,从写简单的博客开始我的学习我有 3 张 table

Table 1 'news'
---------------------------------
id | title | slug | text | image |
---------------------------------
Table 2 'categories'
----------
id | name |
----------
Table 3 'news_cat'
---------------------------
id | news_id | category_id |
---------------------------
in this table `id` is autoincrement

我想看看我的 View 页面中的“新闻”帖子属于哪些类别

查看文件

<?php foreach ($news as $news_item): ?>

<?php echo $news_item['title'] ?>

<p><?=$news_item['text'] ?>
<? foreach($news_item['cat_data'] as $cat_data):?>
The category is:<?=$cat_data ?>

<?php endforeach;?>

<?php if(!empty($news_item['image'])) { ?>
<img src ="/uploads/<?=$news_item['image'];?>">
<?php } ?>

<a href="news/<?=$news_item['slug'] ?>">View article</a>

Controller

public function index()
{

$data['news'] = $this->news_model->get_news();

foreach ($data['news'] as $key => $value) :
$id = $data['news'][$key]['id'];
$data['news'][$key]['cat_data'] = $this->categories_model->get_by_id($id);
// IN THIS I HAVE QUESTION, how insert in my array several values by method get_by_id() and what must have this method

$data['title'] = 'News archive';
$this->load->view('templates/header', $data);
$this->load->view('news/index', $data);
$this->load->view('templates/footer');

}

型号 公共(public)函数 get_by_id($id) {

  in this model i think i need use JOIN, but how i don`t know

}

最佳答案

希望下面的代码示例可以帮助您..如果我理解您的问题,这将为您提供类别名称和 id 值的列表

$this->db->select('categories.name,categories.id');
$this->db->from('categories');
$this->db->join('news_cat',"news_cat.category_id= categories.id");
$query = $this->db->get();
$data['category_list']=$query->result_array();

关于php - 代码点火器。从数据库中获取3个表中的值(多对多),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22809858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com