Write to multiple tables in joomla component?

后端 未结 2 602
眼角桃花
眼角桃花 2020-12-29 12:29

I\'m trying to create a component (front end) that uses multiple tables. I found 1 or 2 post that partially answer to the question but none really does. The point seems alwa

2条回答
  •  抹茶落季
    2020-12-29 13:28

    I finally made it. As I spent many hours on this and found that a lot of people where looking for an answer, here is how I did.

    I suppose you know how to create a component, using the standard MVC structure:

    1. Component entry point
    2. Component controller
    3. Eventually component router
    4. Component view
    5. Component model
    6. Component controller

    In model components\my_component\models\my_model.php create your own save function

    public function save($data)
    {
        // Initialise variables.
        $userId = (!empty($data['id'])) ? $data['id'] : (int)$this->getState('user.id');
        $user = JFactory::getUser();
    
        $table_one = $this->getTable('TableOne', 'MyComponentTable', array());
        $table_two = $this->getTable('TableTwo', 'MyComponentTable', array());
    
        // Bind the data.
        if (!$table_one->bind($data))
        {
            $this->setError(JText::sprintf('USERS PROFILE BIND FAILED', $user->getError()));
            return false;
        }
    
        if (!$table_two->bind($data))
        {
            $this->setError(JText::sprintf('USERS PROFILE BIND FAILED', $user->getError()));
            return false;
        }
    
        // Store the data.
        if (!$table_one->save($data))
        {
            $this->setError($user->getError());
            return false;
        }
    
        if (!$table_two->save($data))
        {
            $this->setError($user->getError());
            return false;
        }
    
        return $user->id;
    }
    

    Of course, you need the getTable function called in the save function

    public function getTable($type = 'TableOne', $prefix = 'MyComponentTable', $config = array())
    {
        // call the administrator\components\com_mycomponent\tables\__tablename__.php
        $this->addTablePath(JPATH_COMPONENT_ADMINISTRATOR . '/tables');
        return JTable::getInstance($type, $prefix, $config);
    }
    

    And it works! So simple! Of course, as I said in my question the whole $data is sent to the parent save() function to with data that are not necessary for table_one or table_two. It works this way with the standard joomla structure (no hack or direct query in the code).

    Hope it helps.

提交回复
热议问题