views:

81

answers:

2

posts and tags have a many-to-many relationship(pretty much like stackoverflow),so the code to do it without an ORM should be:

$dml = "insert into posts(title,body,created) value($title,'{$_POST['post-text']}',now())";
mysql_query($dml,$con);
$pid = mysql_insert_id($con);
//deal with tags

if(isset($_POST['tagnames']))
{
 $tags = preg_split('/\s+/',trim($_POST['tagnames']));
 $list = "('".implode("',1),('", $tags)."',1)";
 $dml = "insert into tags(name,count) values $list on duplicate key update count=count+1";
 mysql_query($dml,$con);
 $list = "('" . implode("','", $tags) . "')";
 $dml = "insert into post_tags(pid,tagId) select $pid,id from tags where name in $list";
 mysql_query($dml,$con);
}

How to do it with by doctrine?

Suppose that the related classes are already generated from schemas

The difficulty lies in the on duplicate key update part.

To step further,it can be more difficult to handle when someone is editing the posts...

+1  A: 

Instead of managing this relationship yourself you might want to consider using sfDoctrineActAsTaggablePlugin, which will probably make your life easier.

Steve
Thanks!But can you briefly describe the principle to deal with such things?As I have to deal with several other similar issues...
I've spent some time reading the code,it uses `$post->addTag('toto');` to handle `tags`,which doesn't take the benefit of sfForm,which uses the `bind` API to automate lots of stuff,so that we only need to modify the related `model` classes.Conclusion,**behaviors are not the proper tool for user submitted data**.It's more applicable for automatically generated stuff like TimeStampable,Versionable
A: 

Well, for me it looks pretty easy.

$post = new Post();
$tags = Doctrine_Query::create()->from('Tags t')->whereIn('t.name', $_POST['tags'])->execute();
foreach ($tags as $tag) $post->link($tag->get('id'));
$post->save();

Why not read manual first? Also please consider to generate a module with symfony doctrine:generate-module post Post and carefully read generated code.

develop7
Seems you don't understand the usecase I described?In your code there is no logic of inserting new `tags` into database,where the `tags` table has a **unique index** on the column `name`,and also need to update the `count` column which denotes the number of times it's used.It's the **form** processing part of symfony,but the tutos haven't covered such complex usecase so far(I've read through many online resources although..).
Hey, I know these nuances. I just thought you want to handle them by hands, not using someone's plugin.
develop7
Yes,you are right,I want to handle them by hands,as there are several other similar cases,which has no related plugins ready cooked.