2011-11-07 71 views
1

我正在用CodeIgniter和DataMapper編寫簡單的博客,並且存在關係問題。我如何通過DattaMapper的特定標籤獲取帖子。 SQL查詢將是類似的東西:從關係表中獲取數據

SELECT 
    posts.id, 
    posts.title, 
    posts.content, 
    posts.created, 
    tags.name 
FROM 
    posts, 
    posts_tags, 
    tags 
WHERE 
    posts.id = posts_tags.post_id AND 
    posts_tags.tag_id = tags.id AND 
    tag.name = 'php'; 
ORDER BY 
    posts.created DESC; 

PHP代碼:

<?php 
class Post extends DataMapper 
{ 
    public $has_many = array('tag'); 

    public function __construct() 
    { 
     parent::__construct(); 
    } 

    public function getPostsByTags($name, $offset) 
    { 
     // this doesn't work 
     // $this->get_where(array('tags.name', $name), 3, $offset); 
    } 
} 

class Tag extends DataMapper 
{ 
    public $has_many = array('post'); 

    public function __construct() 
    { 
     parent::__construct(); 
    } 
} 

數據庫方案:

enter image description here

有什麼建議?

回答

1

我讀了docu,並認爲這可能是工作:

$this->post->get(); 
foreach ($this->post $post) 
{ 
    foreach ($post->tag->get() as $tag) 
    { ... } 
} 

看起來馬麗娟。我應該給它嘗試自己...

更新read here

$p = new Post(); 
// Get users that are related to the Moderator group 
$p->where_related_tag('name', 'php')->get(); 
+0

但在這個解決方案,我得到的所有帖子,然後檢查其職位具有較佳的標籤名。所以我檢索的數據是不需要這部分數據的。 – PaulP

+0

啊我明白了。爲此找到了一些東西。也許下次你自己閱讀文件? ;) – PiTheNumber

+0

PiTheNumber是正確的 - 你說你有一個標籤列表,並希望得到這些標籤的帖子。所以你可以這樣做:'$ p-> where_related_tag('name','php') - > or_where_related_tag('name','html') - > get();' - 這會給你所有的帖子有任何你使用的標籤。 – swatkins