• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to use Controller and Model in Codeigniter 4

#1
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.
Reply

#2
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();
}
Support Development  • Practical CodeIgniter 3  • Vulcan - CLI Tools for CI4
Reply

#3
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.
Reply

#4
(06-03-2019, 11: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();
}
Reply

#5
(06-03-2019, 11: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.
Support Development  • Practical CodeIgniter 3  • Vulcan - CLI Tools for CI4
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.