嘿伙计们!好吧,我正在尝试编码点火器,但在我看来,我在尝试从表中检索和显示数据时弄得一团糟这是代码片段。
我想检索存储在我的文章表中的所有文章,同时我需要从关系表和名为articleTagRelations和标签的标签表中提取与每篇文章关联的所有标签
表结构:文章表:文章ID,文章内容,日期标签表:标签ID,标签名称articleTagRelation : aricleID,tagID {两者的组合是我的主键}
置信区间模型: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) { 返回$tag; } } } 公共函数 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; $data['articletags'] = $this->getAllTags($row->articleId);我正在尝试获取所有关联标签的数组。 $post=array($data['row'],$data['articletags']); } }else{ 回应"什么也没找到! } 返回$post; }
我的控制器文件》.php我在索引函数中调用此函数 $data['rows'] = $this->blog_model->getAllArticles();然后通过传递数据数组加载视图
现在事情变得混乱的部分在我看来 echo $r->articleId//工作正常 echo $r->articletags->tagId//给我一个错误消息任何人都可以帮助我打印这些标签ID
首先,
您根本不需要 foreach 来获取标签信息,它来自query_result。
喜欢这个。。。
if($qTag->num_rows() > 0){
return $qTag->result();
}
else {
return array(); //return empty array if no tags
}
然后要构建您的文章,请使用getAllArticles()
public function getAllArticles(){
// removed uneccessary select and from
// the below accomplishes the same thing
$this->db->order_by('date','desc');
$query = $this->db->get('Article');
if ( $query->num_rows() > 0 ) {
// store the result in a variable you will end up returning
$articles = $query->result();
// make sure you foreach by reference so that changes you make
// to the interated $article will be made to the actual article
// result
foreach ($articles as &$article) {
// create a new property of your article "tags" and save an
// array of tags in it
$article->tags = $this->getAllTags( $article->articleId );
}
} else {
echo 'nothing found !';
}
return $articles;
}
最后要注意的是,当您现在引用$r->tags
数组时,您可以foreach
它来处理所有标签,或者引用索引,例如$r->tags[3]->tagId
if($qTag->num_rows() > 0){
foreach ($qTag->result() as $tag) {
$tags[] = $tag; //this create the array with the result
}
return $tags;
}
"$r->articletags->tagId"仅在将结果作为对象返回时才有效,请改用"$r->articletags['tagId']"。