• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How use Model and Controller for many functions in CI4

#1
Hello everyone, 
My question is regarding Codeigniter 4.

Okay, so I have one controller Home.php and want to get data from different database tables but need to use only one model UserModel.php. In Codeigniter 3, I can easily call different functions from single model like : $this->model->get_custom_users() OR $this->model->upload_user_image().

I don't know how to do this in CI4. can anyone please help me.
Reply

#2
If you use your own queries you are not restricted to using only one table

Just create your own model and use your own queries like you did in CI 3.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#3
(06-03-2019, 10:33 AM)InsiteFX Wrote: If you use your own queries you are not restricted to using only one table

Just create your own model and use your own queries like you did in CI 3.

Can I have simple basic model that is like CI 3 with simple function getting data from one table and how to call that in controller for reference. 

I tried creating UserModel.php and did code like this : 

Quote:UserModel.php
PHP Code:
<?php namespace App\Models;

use 
CodeIgniter\Database\ConnectionInterface;
use 
CodeIgniter\Model;

class 
UserModel extends Model
{
 
   protected $db;

 
   public function __construct(ConnectionInterface &$db)
 
   {
 
       $this->db =& $db;
 
   }

 
   public function get_packages() {
 
       $this->db->select('*');
 
       $this->db->from('package');
 
       $this->db->where(array('price !='=> '0','enabled'=>'1'));
 
       return  $this->db->get()->result_array();
 
   }
}
?>


And my controller is like this :
Quote:Site.php
PHP Code:
<?php namespace App\Controllers;

use 
CodeIgniter\Controller;
use 
App\Models\UserModel;

class 
Site extends Controller
{
   public function 
pricing()
   {
    
$db = \Config\Database::connect();
    
$UserModel = new UserModel($db);
    
$data $UserModel->get_packages();
    echo 
"<pre>"print_r($data); echo "</pre>"; exit();
   }



What is the wrong I am doing here ?
Reply

#4
Things have changed a little since CI3, so you might want to read over the Query Builder section of the user_guide, especially at the top. But basically, you won't use the from part of the code. Instead you'd do something like:

Code:
public function get_packages() {
        $builder = $this->db->table('package');
                ->where(array('price !='=> '0','enabled'=>'1'));
        return  $builder->get()->getResultArray();
    }
Support Development  • Practical CodeIgniter 3  • Vulcan - CLI Tools for CI4
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


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