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();
    }
}

数据库方案:

在此处输入图像描述

有什么建议么?

4

1 回答 1

1

我阅读了文档并认为这可行:

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

看起来很棒。我应该自己试一试...

更新在这里阅读

$p = new Post();
// Get users that are related to the Moderator group
$p->where_related_tag('name', 'php')->get();
于 2011-11-07T16:44:45.403 回答