从关系中的表中获取数据

时间:2011-11-07 16:22:14

标签: codeigniter codeigniter-datamapper

我正在用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 个答案:

答案 0 :(得分: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();