开发者

Using HABTM relationships in cakephp plugins with unique set to false

I am working on a plugin for our CakePHP CMS that will handle blogs. When getting to the tags I needed to set the HABTM relationship to unique = false to be able add tags to a post without having to reset them all.

The BlogPost model looks like this

class BlogPost extends AppModel {
    var $name = 'BlogPost';
    var $actsAs = array('Core.WhoDidIt', 'Containable');
    var $hasMany = array('Blog.BlogPostComment');
    var $hasAndBelongsToMany = array('Blog.BlogTag' => array('unique' => false), 'Blog.BlogCategory');
}

The BlogTag model looks like this

class BlogTag extends AppModel {
    var $name = 'BlogTag';
    var $actsAs = array('Containable');
    var $hasAndBelongsToMany = array('Blog.BlogPost');
}

The SQL error I am getting when I have the unique => true setting in the HABTM relationship between the BlogPost and BlogTag is

Query: SELECT `Blog`.`BlogTag`.`id`, `Blog`.`BlogTag`.`name`, `Blog`.`BlogTag`.`slug`, `Blog`.`BlogTag`.`created_by`, `Blog`.`BlogTag`.`modified_by`, `Blog`.`BlogTag`.`created`, `Blog`.`BlogTag`.开发者_运维问答`modified`, `BlogPostsBlogTag`.`blog_post_id`, `BlogPostsBlogTag`.`blog_tag_id` FROM `blog_tags` AS `Blog`.`BlogTag` JOIN `blog_posts_blog_tags` AS `BlogPostsBlogTag` ON (`BlogPostsBlogTag`.`blog_post_id` = 4 AND `BlogPostsBlogTag`.`blog_tag_id` = `Blog`.`BlogTag`.`id`)

As you can see it is trying to set the blog_tags table to 'Blog'.'BlogTag. which isn't a valid MySQL name.

When I remove the unique => true from the relationship it all works find and I can save one tag but when adding another it just erases the first one and puts the new one in its place.

Does anyone have any ideas? is it a bug or am I just missing something?

Cheers, Dean


Dean

So do you have the tables blog_posts_blog_tags?

To quote the CakePHP literature on HABTM relationships

We'll need to set up an extra table in the database to handle HABTM associations. This new join table's name needs to include the names of both models involved, in alphabetical order, and separated with an underscore ( _ ).

So ( dropping the Blog bit for readability !) you need your posts tables, your tags table and your posts_tags table and then the HABTM definition is

class Post extends AppModel {
    var $name = 'Post';   
    var $hasAndBelongsToMany = array(
        'Tag' =>
            array(
                'className'              => 'Tag',
                'joinTable'              => 'posts_tags',
                'foreignKey'             => 'post_id',
                'associationForeignKey'  => 'tag_id',
                'unique'                 => true,
            )
    );
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜