CodeIgniter Forums
How to use Controller and Model in Codeigniter 4 - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Discussion (https://forum.codeigniter.com/forum-31.html)
+--- Thread: How to use Controller and Model in Codeigniter 4 (/thread-73771.html)



How to use Controller and Model in Codeigniter 4 - ashok.desai64 - 06-03-2019

Hello everyone, This is related to codeigniter 4.

Actually I need to use same model but different functions (3 different functions) to get data in controller. I don't understand how to do it all 3 functions are for different tables. In codeigniter 3, I can easily get data from single model using different functions like this : 


PHP Code:
$this->load->model('User_model');
$this->model->data_function_one('table1');
$this->model->data_function_two('table2');
$this->model->data_function_three('table3'); 
Can anyone please help me how to do it in Codeigniter 4.


RE: How to use Controller and Model in Codeigniter 4 - kilishan - 06-03-2019

Models are just classes so loading a model is simply:

Code:
$userModel = new UserModel();

Typically models have a 1 model-to 1 table relationship. If you need to use a different table within one of the functions you can use the Model's builder() method:

Code:
public function data_function_one()
{
    $builder = $this->builder('table1')->whateverYouNeedNext();
}



RE: How to use Controller and Model in Codeigniter 4 - ashok.desai64 - 06-03-2019

Thanks very much. So you mean in Builder, I have to write query? can you please give me sample for builder file with query if possible.


RE: How to use Controller and Model in Codeigniter 4 - titounnes - 06-04-2019

(06-03-2019, 10:04 PM)ashok.desai64 Wrote: Thanks very much. So you mean in Builder, I have to write query? can you please give me sample for builder file with query if possible.
You can try this code.
$user = new UserModek();
$query = $user->where('email', $email)->find();
in class userModel you can add method for complex query
function queryJoin()
{
return $this->join('users_groups', 'user.id=users_groups.user_id', 'inner')
->where('users_groups.group_id', 1)
->findAll();
}


RE: How to use Controller and Model in Codeigniter 4 - kilishan - 06-04-2019

(06-03-2019, 10:04 PM)ashok.desai64 Wrote: Thanks very much. So you mean in Builder, I have to write query? can you please give me sample for builder file with query if possible.

builder just returns an instance of the Query Builder for whatever table name you pass to it. If no table is passed, it does the default one for the model. The Query Builder is exactly what you're used to generating queries with so write your queries as you always have and you're fine.