How to create model and use in controller file

Deepak Tailor Image
Deepak Tailor - Dec 07 2020
How to create model  and use in controller file

Models provide a way to interact with a specific table in your database. They come out of the box with helper methods for much of the standard ways you would need to interact with a database table, including finding records, updating records, deleting records, and more.

Create your model
<?php 
namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{

}
Access model in controller
protected $userModel;
public function __construct()
{
	$this->userModel = model('App\Models\UserModel');
	$db = db_connect('seller');
	$this->userModel = model('Usermodel', true, $db);
}
Configuration your model
protected $table      = 'users';
protected $returnType = 'array';
protected $allowedFields = ['id','name'];
find function in modeling data

Find function uses single row to match. This function checks the argument at the primary key. And it returns the value in the object or array format.

public function find_data()
{
	$result = $this->userModel->find(1);
	echo "<pre>";
	print_r($result);
}

public function find_data()
{
	$result = $this->userModel->find([1,3]);
	echo "<pre>";
	print_r($result);
}
Find column value

To fetch the values of a column, we use the Find column function.

public function find_column()
{
	$result = 
	$this->userModel->findColumn('salary');
	echo "<pre>";
	print_r($result);
}
Find all records
public function find_all()
{
	$result = $this->userModel->findAll();
	echo "<pre>";
	print_r($result);
}
Find all records with where arguments
public function find_all()
{
	$result = $this->userModel
	->where('id',2)
	->findAll();
	echo "<pre>";
	print_r($result);
}

public function find_all()
{
	$result = $this->userModel
	->where('id!=',2)
	->findAll();
	echo "<pre>";
	print_r($result);
}
Find first records

If the first record of the table has to be fetched, then we use the first function.

public function find_first()
{
	$result = 
	$this->userModel->first();
	echo "<pre>";
	print_r($result);
}
Find first records with where arguments
public function find_first()
{
	$result = 
	$this->userModel
	->where('id>',2)
	->first();
	echo "<pre>";
	print_r($result);
}
Deepak Tailor Image
Deepak Tailor

My name is Deepak tailor as a fullstack developer. I have been in the IT industry for the last 5 years. For professional and customize web development, you can send inquiry on our email.
----
You can contact him at support@fulstackdev.com