/** * Responds to {@link CActiveRecord::onAfterSave} event. * Overrides this method if you want to handle the corresponding event of the {@link CBehavior::owner owner}. * @param CModelEvent $event event parameter */ public function afterSave($event) { $data = array(); $objectId = $this->getOwner()->{$this->objectAttribute}; if ($this->useActiveField) { $data = $this->getOwner()->{$this->name}; if (!is_array($data) && !is_object($data)) { $data = array((int) $data); } } else { if (isset($_POST[$this->name])) { $data = $_POST[$this->name]; if (!is_array($data) && !is_object($data)) { $data = array((int) $data); } } } //delete old $sql = "DELETE FROM " . SITE_ID . '_' . "taxonomy_index t" . "\n USING " . SITE_ID . '_' . "taxonomy_term tt, " . SITE_ID . '_' . "taxonomy_vocabulary tv" . "\n WHERE tt.id = t.term_id AND tv.id = tt.v_id" . (is_numeric($this->taxonomy) ? "\n AND (tv.id = :id)" : "\n AND (tv.alias = :alias)") . "\n AND tv.module = :module AND t.object_id = :object_id"; if (count($data)) { foreach ($data as $index => $val) { $data[$index] = CPropertyValue::ensureInteger($val); } $dataString = implode(',', $data); $sql .= "\n AND t.term_id NOT IN ({$dataString})"; } $command = TermRelation::model()->getDbConnection()->createCommand($sql); if (is_numeric($this->taxonomy)) { $command->bindParam(":id", $this->taxonomy, PDO::PARAM_INT); } else { $command->bindParam(":alias", $this->taxonomy, PDO::PARAM_STR); } $command->bindParam(":module", $this->module, PDO::PARAM_STR); $command->bindParam(":object_id", $objectId, PDO::PARAM_INT); $command->execute(); //update/create if (count($data)) { foreach ($data as $val) { $relation = TermRelation::model()->findByAttributes(array('object_id' => $objectId, 'term_id' => $val)); if (!is_object($relation)) { $relation = new TermRelation(); } $relation->object_id = $objectId; $relation->term_id = $val; if (!$relation->save()) { Yii::log(CVarDumper::dumpAsString($relation->getErrors()), CLogger::LEVEL_ERROR); } } } }
/** * 设置文章分类 * * @param intger|array $categories * * @return boolean */ public function setCategories($categories) { is_array($categories) || ($categories = array($categories)); //如果不同才存 if (Input::get('old_category', '') != join(',', $categories)) { $this->termRelation()->delete(); $termRelMultiData = array_map(function ($categoryId) { return array('object_id' => $this->id, 'category_id' => $categoryId); }, $categories); //一次性写入多条 //请参考:http://www.golaravel.com/docs/4.1/queries/#inserts return false !== TermRelation::insert($termRelMultiData); } return true; }