From ecf50815f6ccc80bb9c9cc9327bbb8a6c9392a16 Mon Sep 17 00:00:00 2001 From: Stephan Miller Date: Mon, 9 Dec 2013 20:29:09 -0600 Subject: [PATCH] Preliminary end of chapter 4 - tags working --- app/controllers/PostsController.php | 24 ++--------- app/models/Posts.php | 62 +++++++++++++++++++++-------- 2 files changed, 50 insertions(+), 36 deletions(-) diff --git a/app/controllers/PostsController.php b/app/controllers/PostsController.php index bf7a532..a9bca83 100755 --- a/app/controllers/PostsController.php +++ b/app/controllers/PostsController.php @@ -151,16 +151,8 @@ public function createAction() { $success = $post->save(); - $rawTags = explode(",",$this->request->getPost("tags", array("trim", "lower"))); - foreach ($rawTags as $t){ - $tag = new Tags(); - $tag->tag = $t; - $tag->save(); - $postTag = new PostTags(); - $postTag->posts_id = $post->id; - $postTag->tags_id = $tag->id; - $postTag->save(); - } + $tags = explode(",",$this->request->getPost("tags", array("trim", "lower"))); + Posts::addTags($tags,$post->id); if (!$success) { foreach ($post->getMessages() as $message) { @@ -222,16 +214,8 @@ public function saveAction() { $success = $post->save(); - $rawTags = explode(",",$this->request->getPost("tags", array("trim", "lower"))); - foreach ($rawTags as $t){ - $tag = new Tags(); - $tag->tag = $t; - $tag->save(); - $postTag = new PostTags(); - $postTag->posts_id = $post->id; - $postTag->tags_id = $tag->id; - $postTag->save(); - } + $tags = explode(",",$this->request->getPost("tags", array("trim", "lower"))); + Posts::addTags($tags,$post->id); if (!$success) { diff --git a/app/models/Posts.php b/app/models/Posts.php index e1ef26b..271f69c 100755 --- a/app/models/Posts.php +++ b/app/models/Posts.php @@ -1,72 +1,102 @@ hasMany("id", "Comments", "posts_id", NULL); - $this->hasMany("id", "PostTags", "posts_id", NULL); - $this->belongsTo("users_id", "Users", "id", array("foreignKey"=>true)); + public function initialize() { + $this->hasMany("id", "Comments", "posts_id", NULL); + $this->hasMany("id", "PostTags", "posts_id", NULL); + $this->belongsTo("users_id", "Users", "id", array("foreignKey" => true)); + + } + /** + * Adds tags to a post + */ + static function addTags($tags, $post_id) { + foreach ($tags as $t) { + $t = trim($t); + $tag = Tags::findFirst(array("tag = '$t'")); + if (!$tag) { + $tag = new Tags(); + $tag->tag = $t; + $tag->save(); + } + $postTag = PostTags::findFirst( + array( + "conditions" => "posts_id = ?1 AND tags_id = ?2", + "bind" => array( + 1 => $post_id, + 2 => $tag->id + ) + ) + ); + if (!$postTag) { + $postTag = new PostTags(); + $postTag->posts_id = $post_id; + $postTag->tags_id = $tag->id; + $postTag->save(); + } + unset($tag); + unset($postTag); + } } }