/** * * Assign tags to photos. Tags just assign to photos (without removing if exist for concrete photo) * @param array|int $photo_ids * @param array|int $tag_ids * @throws Exception */ public function assign($photo_ids, $tag_ids = array()) { if (!$photo_ids) { throw new Exception("Can't assign tags: unkown any photo id"); } $photo_ids = (array) $photo_ids; $photo_model = new photosPhotoModel(); $where = $photo_model->getWhereByField('id', $photo_ids); // define if we have parents for any given photo $parents = $photo_model->select('parent_id')->where($where . ' AND parent_id != 0')->fetchAll('parent_id', true); // we have parents - we have stacks if ($parents) { $photo_ids = array_merge($photo_ids, array_keys($parents)); } $where = $photo_model->getWhereByField('parent_id', $photo_ids); // get children for every stack $children = $photo_model->select('id')->where($where)->fetchAll('id', true); if ($children) { $photo_ids = array_merge($photo_ids, array_keys($children)); } // remove doubles $photo_ids = array_unique($photo_ids); $tag_ids = (array) $tag_ids; $sql = "SELECT * FROM {$this->table} "; if ($where = $this->getWhereByField('photo_id', $photo_ids)) { $sql .= " WHERE {$where}"; } $existed_tags = array(); foreach ($this->query($sql) as $item) { $existed_tags[$item['photo_id']][$item['tag_id']] = true; } foreach ($tag_ids as $tag_id) { $add = array(); foreach ($photo_ids as $photo_id) { if (!isset($existed_tags[$photo_id][$tag_id])) { $add[] = array('photo_id' => $photo_id, 'tag_id' => $tag_id); } } if (!empty($add)) { if ($this->multiInsert($add)) { $added_count = count($add); $this->query("UPDATE photos_tag SET count = count + {$added_count} WHERE id = i:id", array('id' => $tag_id)); } } } }