Updating assets

From Joomla! Documentation

This mainly applies to third party components are who tracking assets on a per item basis.

If your users uninstall the component without removing the database, then reinstall, or import a database, the assets in the #__assets table might not match the asset_id in your component tables, or the $parent_id in the #__assets table may be incorrect in the asset entries.

I wrote a small function that could be run to fix the assets. It's the only safe way I've found, by using JTable.

Here is the function:

public function fixAssets()

   {
       
      	$db = JFactory::getDBO();
       @set_time_limit(300);
       //Get all of the table names
       $objects = $this->getObjects();
       foreach ($objects as $object)
       {
           @set_time_limit(300);
           $query = 'SELECT id FROM '.$object['name'];
           $db->setQuery($query);
           $db->query();
           $datarows = $db->loadObjectList();
           if ($datarows)
           {
               foreach ($datarows as $data)
               {
                   JTable::addIncludePath(JPATH_COMPONENT.'/tables');
                   $table = JTable::getInstance($object['assetname'], 'Table', array('dbo' => $db));
                   if ($data->id)
                   {
                       
                      try {$table->load($data->id);}
                       catch (Exception $e) {echo 'Caught exception: ',  $e->getMessage(), "\n";}
                       if (!$table->store()) 
                       {
                           $this->setError($db->getErrorMsg());
                           return false;
                       }
                   }
               }
           }
       }
   }

The array $objects is created in a separate function so you have to substitute the name(s) of your tables for $object['assetname']. It would need to be the name of your table class in your component tables folder.

Basically this loads the id of each table row into an array $datarows, then uses JTable to load() the data from row using id as the key field, then store() which will invoke whatever rules you have set up and resave it to the assets table.