public function saveTags($posted_tags, $product_id) { $tags = explode(",", $posted_tags); if (!$tags) { return; } ProductTagProducts::deleteAll(["product_id" => $product_id]); foreach ($tags as $tagname) { $tagname = trim($tagname); $sql = "SELECT id FROM product_tags WHERE tag_name = :tag_name"; $result = Yii::$app->db->createCommand($sql)->bindValue(":tag_name", $tagname, \PDO::PARAM_STR)->queryOne(); if ($result) { $id = $result["id"]; } else { $model = new ProductTags(); $model->tag_name = $tagname; $model->save(); $id = $model->id; } $tagproductModel = new ProductTagProducts(); $tagproductModel->tag_id = $id; $tagproductModel->product_id = $product_id; $tagproductModel->save(); } }