2
votes

Good evening.

Mabye I am blind, but I can't find a solution to this: I have 2 models, Post and Tag with fields post_text and tag_name, where Post habtm Tag.

Now I have form, where I input post_text and couple of tag_names. And I would like to save each of these Tags, keep them unique (so if the Tag is already in DB, don't save it, just get the ID of it), then save the Post and finaly relate the Post with the Tags via posts_tags table.

Now everybody tells me: leave it on Cake, it can do all this work for you! OK, I would love to, but how should my $this->data array look like?

I am trying Tag.tag_name, Post.Tag.tag_name, Post.Tag.0.tag_name, Post.PostsTag.0.tag_name, Tag.Tag.tag_name, Post.PostsTag.Tag.0.tag_name, ...

I am trying save(), saveAll(), ... nothing works. And all the examples on the web (including Cake Book) are working with Tag IDs, not Tag names.

Is there a way (I mean $this->data array form), that I can post to $this->Post->save() or saveAll() and it will do all the magic for me?

Thank you very much.

Josh.T.

1
AFAIK you cannot create tags this way, you'd have to create the tags first...Dunhamzzz
Well, in that case, I am looking for a saveUnique() method in the Tag model, that will either save a new Tag or read the already saved Tag from DB and set the model's ID. So I don't have to solve this in Controller. It's not difficult to create such a method, but when I tried to find some inspiration, everyone who ever asked that question was given the answer: "Don't do that, use default Cake functionality." Gee, it's a vicious circle :-)Josh.T.

1 Answers

0
votes

Afraid you'll have to write the saveUnique() method yourself, someone may correct me but I don't think cake's automagic goes that far.

You'll basically have to check for each tag, if it exists, get the id(s) into an array - otherwise make it and get the id(s). Then pretty much save that array as a standard habtm with the original post.

It may even be worth using someform of AutoComplete on the add form to get tags that already exist, and then only have to create the one's that don't exist and then saving them + the habtm relationship.