How to use multiple models in joomla MVC Component

2020-02-10 08:37发布

问题:

I am using different model in joomla than view's own model that is similar to its name by assigning it from controller, like:

         $view->setModel($this->getModel('user'));

Now how can I use its method getSingleUser($user_id) in view. In an example in joomla documentation , it is using is some thing like this:

$this->get("data1","model2");

So I assume data1 is name of method in model2? If so then how can I pass argument that is userid in my case. I know this is easy thing that many of joomla developers have done but I am sort of jack of all sort of developer and new to joomla so I am expecting you guys to tell me .

回答1:

First approach

I did this by modifying the controller as follows (this is the controller for user)

function doThis(){ // the action in the controller "user" 
    // We will add a second model "bills"
    $model = $this->getModel ( 'user' ); // get first model
    $view  = $this->getView  ( 'user', 'html'  ); // get view we want to use
    $view->setModel( $model, true );  // true is for the default model  
    $billsModel = &$this->getModel ( 'bills' ); // get second model     
    $view->setModel( $billsModel );             
    $view->display(); // now our view has both models at hand           
}

In the view you can then simply do your operations on the models

function display($tpl = null){              
    $userModel = &$this->getModel(); // get default model
    $billsModel = &$this->getModel('bills'); // get second model

    // do something nice with the models

    parent::display($tpl); // now display the layout            
}

Alternative approach

In the view directly load the model:

function display($tpl = null){
 // assuming the model's class is MycomponentModelBills 
 // second paramater is the model prefix    
        $actionsModel = & JModel::getInstance('bills', 'MycomponentModel'); 
}