嘿伙计们! 好吧,我正在尝试使用 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
最佳答案
首先,您根本不需要 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
关于php - 在 CodeIgniter 2.0 中返回并使用数据库中的多维记录数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5987951/