How to deal with m2m relationship(posts and tags) by doctrine(in symfony)?

和自甴很熟 提交于 2019-12-13 09:50:00

问题


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:


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




回答2:


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.



来源:https://stackoverflow.com/questions/2392827/how-to-deal-with-m2m-relationshipposts-and-tags-by-doctrinein-symfony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!