我想为我的每个帖子显示类别。通过教程,我能够创建MY_Model
,但我无法在每个帖子上显示类别。
这是我的后模型:
<?php
class Post_m extends MY_Model
{
protected $_table_name = 'posts';
protected $_order_by = 'pubdate desc, id desc';
protected $_timestamps = TRUE;
public $rules = array(
'pubdate' => array(
'field' => 'pubdate',
'label' => 'Publication date',
'rules' => 'trim|required|exact_length[10]'
),
'title' => array(
'field' => 'title',
'label' => 'Title',
'rules' => 'trim|required|max_length[100]'
),
'slug' => array(
'field' => 'slug',
'label' => 'Slug',
'rules' => 'trim|required|max_length[100]|url_title'
),
'body' => array(
'field' => 'body',
'label' => 'Body',
'rules' => 'trim|required'
)
);
public function get_new ()
{
$post = new stdClass();
$post->title = '';
$post->slug = '';
$post->body = '';
$post->name = '';
$post->post_image = '';
$post->pubdate = date('Y-m-d');
return $post;
}
public function set_published(){
$this->db->where('pubdate <=', date('Y-m-d'));
}
public function get_recent($limit = 3){
// Fetch a limited number of recent articles
$limit = (int) $limit;
$this->set_published();
$this->db->limit($limit);
return parent::get();
}
public function get_categories()
{
$this->db->order_by('name');
$query = $this->db->get('categories');
return $query->result_array();
}
}
?>
现在我想按名称显示类别。这就是我目前所拥有的:
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>#</th>
<th>Title</th>
<th>Posts</th>
<th>Category</th>
<th>Date</th>
<th></th>
</tr>
</thead>
<tbody>
<?php if(count($posts)): foreach ($posts as $key => $post) if ($key >= 1) { ?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo anchor('admin/posts/edit/' . $post->id, $post->title); ?></td>
<td><?php echo e(limit_to_numwords(strip_tags($post->body), 10)); ?></td>
<td><?php echo $post->category_id; ?></td>
<td><?php echo $post->pubdate; ?></td>
<td><?php echo btn_edit('admin/posts/edit/' . $post->id); ?></td>
<td><?php echo btn_delete('admin/posts/delete/' . $post->id); ?></td>
</tr>
<?php } ?>
<?php else: ?>
<tr>
<td class="center" colspan="3">We could not find any articles.</td>
</tr>
<?php endif; ?>
</tbody>
</table>
</div>
如果您注意到,我添加了$post->category_id
,但它只显示INT,而不显示类别的名称。
求你了,救命!!
你还没有发布你的控制器,所以我不确定你是如何使用当前模型的,但如果你也想显示每个帖子所属类别的名称,你需要使用一个连接,比如:
public function get_posts() {
$this->db->select('
categories.id AS category_id,
categories.name,
posts.id,
posts.title,
posts.body,
posts.pubdate
');
$this->db->from('posts');
$this->db->join('categories', 'posts.category_id = categories.id');
return $this->db->get()->result_array();
}
这样做的目的是,它从posts表中获取所有行,并且对于每个post行,它还从categories表中获取相应的类别信息(包括名称(。它可以使用每个帖子行中的类别id找到正确的类别信息。然后返回两个表中的信息。