Index: trunk/kernel/units/general/cat_dbitem.php =================================================================== diff -u -r3709 -r3757 --- trunk/kernel/units/general/cat_dbitem.php (.../cat_dbitem.php) (revision 3709) +++ trunk/kernel/units/general/cat_dbitem.php (.../cat_dbitem.php) (revision 3757) @@ -59,7 +59,7 @@ function Update($id=null, $system_update=false) { - $this->VirtualFields['ResourceId'] = true; + $this->VirtualFields['ResourceId'] = Array(); $this->SetDBField('Modified', adodb_mktime() ); $this->SetDBField('ModifiedById', $this->Application->GetVar('u_id')); @@ -68,7 +68,10 @@ $this->generateFilename(); } - return parent::Update($id, $system_update); + $ret = parent::Update($id, $system_update); + + unset($this->VirtualFields['ResourceId']); + return $ret; } function checkFilename() @@ -319,16 +322,47 @@ */ function assignToCategory($category_id, $is_primary = false) { - $check_sql = ' SELECT CategoryId - FROM '.TABLE_PREFIX.'CategoryItems - WHERE (ItemResourceId = '.$this->GetDBField('ResourceId').') AND (PrimaryCat = 1)'; - $primary_category_id = $this->Conn->GetOne($check_sql); - if (!$primary_category_id) $is_primary = true; + $table = TABLE_PREFIX.'CategoryItems'; + $key_clause = '(ItemResourceId = '.$this->GetDBField('ResourceId').')'; - if ($primary_category_id == $category_id) return ; + // get all cateories, where item is in + $sql = 'SELECT PrimaryCat, CategoryId FROM '.$table.' WHERE '.$key_clause; + $item_categories = $this->Conn->GetCol($sql, 'CategoryId'); + if (!$item_categories) { + $item_categories = Array(); + $primary_found = false; + } - $sql = 'INSERT INTO '.TABLE_PREFIX.'CategoryItems (CategoryId,ItemResourceId,PrimaryCat) VALUES (%s,%s,%s)'; - $this->Conn->Query( sprintf($sql, $category_id, $this->GetDBField('ResourceId'), $is_primary ? 1 : 0) ); + // find primary category + foreach ($item_categories as $item_category_id => $primary_found) { + if ($primary_found) { + break; + } + } + + if ($primary_found && ($item_category_id == $category_id) && !$is_primary) { + // want to make primary category as non-primary :( + return true; + } + else if (!$primary_found) { + $is_primary = true; + } + + if ($is_primary && $item_categories) { + // reset primary mark from all other categories + $sql = 'UPDATE '.$table.' SET PrimaryCat = 0 WHERE '.$key_clause; + $this->Conn->Query($sql); + } + + // UPDATE & INSERT instead of REPLACE because CategoryItems table has no primary key defined in database + if (isset($item_categories[$category_id])) { + $sql = 'UPDATE '.$table.' SET PrimaryCat = '.($is_primary ? 1 : 0).' WHERE '.$key_clause.' AND (CategoryId = '.$category_id.')'; + $this->Conn->Query($sql); + } + else { + $sql = 'INSERT INTO '.$table.' (CategoryId,ItemResourceId,PrimaryCat) VALUES (%s,%s,%s)'; + $this->Conn->Query( sprintf($sql, $category_id, $this->GetDBField('ResourceId'), $is_primary ? 1 : 0) ); + } } /**