How to get HABTM associated data using hasOne binding

Posted by Moin on Stack Overflow See other posts from Stack Overflow or by Moin
Published on 2010-12-31T02:25:09Z Indexed on 2010/12/31 2:54 UTC
Read the original article Hit count: 233

Filed under:
|
|
|

Hi,

I am following example documented at http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM

I am trying to retrieve associated data using hasOne.

I created 3 tables posts, tags and posts_tags. I wrote following code to debug Posts.

$this->Post->bindModel(array(
    'hasOne' => array(
        'PostsTag',
        'FilterTag' => array(
            'className' => 'Tag',
            'foreignKey' => false,
            'conditions' => array('FilterTag.id = PostsTag.tag_id')
))));
$output=$this->Post->find('all', array(
        'fields' => array('Post.*')
));
debug($output);

I was expecting output something like below.

Array
(  
    0 => Array
        {
        [Post] => Array
            (
                [id] => 1
                [title] => test post 1
            )
    [Tag] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => php
                )
           [1] => Array
                (
                    [id] => 2
                    [name] => javascript
                )
           [2] => Array
                (
                    [id] => 3
                    [name] => xml
                )
        )
}

But my output do not have Tags at all. Here is what I got.

Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    [id] => 1
                    [title] => test post1
                )

        )

    [1] => Array
        (
            [Post] => Array
                (
                    [id] => 2
                    [title] => test post2
                )

        )
)

How do I get associated tags along with the post.

I know I am missing something, but unable to figure out. Any help would be highly appreciated.

© Stack Overflow or respective owner

Related posts about php

Related posts about cakephp