public function savePostTopics($postId, $topics) { // Explode the topics by comma, so we have an array to run through $topics = explode(',', $topics); // Array for collecting all the data $collection = array(); foreach($topics as $topic) { // Trim it so remove unwanted white spaces in the beginning and the end. $topic = trim($topic); // Make it all lowercase for consistency of tag names $topic = strtolower($topic); // Check if we already have a topic like this $controlFind = $this->find( 'first', array( 'conditions' => array( 'title' => $topic ), 'recursive' => -1 ) ); // No record found if(!$controlFind) { $this->create(); if( !$this->save( array( 'title' => $topic ) ) ) { // If only one saving fails we stop the whole loop and method. return false; } else { $temp = array( 'TopicPost' => array( 'topic_id' => $this->id, 'post_id' => $postId ) ); } } else { $temp = array( 'TopicPost' => array( 'topic_id' => $controlFind['Topic']['id'], 'post_id' => $postId ) ); } $collection[] = $temp; } return $this->TopicPost->saveMany($collection, array('validate' => false)); }