大家好 !好吧,我正在尝试使用codeigniter,但在我看来,在尝试检索并显示表中的数据时,我已经做了一些混乱,这里是代码片段 .
我想要检索存储在我的文章表中的所有文章以及我需要从关系表中分别提取与每篇文章相关联的所有标签以及分别称为articleTagRelation和标签的标签表
Table structure :
Article table : articleID, articleContent, date
Tags table : tagID, tagName
articleTagRelation : aricleID,tagID {Combination of both is my primary key}
CI model :
article_model.php
public function getAllTags($postId){
$this->db->select('articleTagRelation.tagId as tagId, articleTagRelation.postId as postId, article.tagName as tagName,');
$this->db->from('articleTagRelation');
$this->db->join('Tags','Tags.tagId = articleTagRelation.tagId');
$this->db->where('ArticleTagRelation.articleId',$postId);
$qTag = $this->db->get();
if($qTag->num_rows() > 0){
foreach ($qTag->result() as $tag) {
return $tag;
}
}
}
public function getAllArticles(){
$this->db->select('*');
$this->db->from('Article');
$this->db->order_by('date','desc');
$query=$this->db->get();
if($query->num_rows()>0){
foreach ($query->result() as $row) {
$data['row'] = $row;
$data['articletags'] = $this->getAllTags($row->articleId); // I'm trying to get get a array of all the associate tags.
$post=array($data['row'],$data['articletags']);
}
}else{
echo 'nothing found !';
}
return $post;
}
my controller file
article.php
I'm calling this function in the index function
$data['rows'] = $this->blog_model->getAllArticles();
and then loading the view by passing the data array
now the part where things get messy
in my view
echo $r->articleId // works fine
echo $r->articletags->tagId //gives me a error message
Can any one help me out in printing those tagIds
2 回答
首先,您根本不需要foreach来获取标记信息,它从query_result返回 .
像这样...
然后构建您的文章,使用
getAllArticles()
执行此操作最后要注意的是,当你现在引用
$r->tags
这是一个数组时,你可以foreach
它来处理所有标签,或者引用像$r->tags[3]->tagId
这样的索引“$ r-> articletags-> tagId”仅在将结果作为对象返回时才有效,请使用“$ r-> articletags ['tagId']” .