1

I am writing simple blog with CodeIgniter and DataMapper and I have problem with relation. How can I get posts by particularly tags with DattaMapper. SQL query will be something like that:

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 code:

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

Database scheme:

enter image description here

Any suggestions?

PaulP
  • 1,925
  • 2
  • 20
  • 25

1 Answers1

1

I read the docu and think this could work:

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

Looks greate. I should give it try myself...

Update, read here:

$p = new Post();
// Get users that are related to the Moderator group
$p->where_related_tag('name', 'php')->get();
PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
  • But in this solution I get all posts and then check which post has preferred tag name. So I retrieve data in which part of this data is not needed. – PaulP Nov 07 '11 at 16:58
  • ah I see. found something for this. Maybe next time you read the docu yourself? ;) – PiTheNumber Nov 07 '11 at 17:04
  • PiTheNumber is correct - You're saying you have a list of tags and want to get the posts that have those tags. So you can do this: `$p->where_related_tag('name', 'php')->or_where_related_tag('name', 'html')->get();` -- this will give you all of the posts that have any of the tags that you use. – swatkins Nov 07 '11 at 17:10
  • @swatkins I know PiTheNumber correct now, but my comment was before update – PaulP Nov 07 '11 at 18:26