Saturday, July 13, 2024
CodeIgniter - model
We call everything in PHP (or any language) that works with the database a model
data. These are classes, validation and wrapper functions/methods.
Before this, take a look at this
post and it wouldn't be a bad idea to browse through the querybuilder
documentation.
In CodeIgniter, we enter the access data in the .env file.
#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------
database.default.hostname = localhost
database.default.database = ci4_app
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
We create the model file with:
php spark make:model User --suffix
The model files are in the “/app/Models” directory. Such a file is
connected to one table. There we determine which columns are allowed:
protected $allowedFields = [
"name",
"email",
];
There we also have validation settings:
// Validation
protected $validationRules = [
"name" => "required|min_length[3]|max_length[120]",
"email" => "required|valid_email|min_length[5]|is_unique[tbl_members.email]",
];
protected $validationMessages = [
"name" => [
"required" => "Name is required",
"min_length" => "Minimum length of name should be 3 chars",
"max_length" => "Maximum length of name should be 128 chars",
],
"email" => [
"required" => "Email needed",
"valid_email" => "Please provide a valid email address"
],
];
We have more validation filters on the page here:
https://codeigniter4.github.io/userguide/libraries/validation.html#available-rules
Validation errors
We can check the correctness of the model methods with the returned bool (true/false) value. And if we have "CI_ENVIRONMENT = development" in the .env file instead of a negative boolean, the returned value will contain a description of the error.
if ($employeeModel->insert($data))
{
$this->response->setStatusCode(200);
return $this->response->setJSON(['OK']);
}
otherwise
{
$this->response->setStatusCode(500);
return $this->response->setJSON(['FAIL']);
}
We also get possible errors with:
$userModel->errors();
We can pass the above as a template variable:
return view('moj-template', [
'errors' => $memberModel->errors()
]);
Controller
First we need to import the model file:
use App\Models\UserModel;
Then in the method:
$userModel = new UserModel();
$data = [
[
"name" => "damir",
"email" => "damir@gmail.com",
],
[
"name" => "dsijak",
"email" => "dsijak@gmail.com",
],
];
$return_data = $userModel->insertBatch($data);
If we want to insert only one row:
$return_data = $userModel->insert($data);
To select only one row by id:
$worksiteModel = new WorksiteModel();
$query = $worksiteModel->getWhere(['id' => $worksiteId]);
$result = $query->getResult();
//or
$worksiteModel = new WorksiteModel();
$query = $worksiteModel->select('*')->where('id', $id)->get();
$result = $query->getResult();
If we already have data in the database, we renew the data in the database in this way:
$userModel = new UserModel();
$data = [
"name" => "Novo ime",
"email" => "novoIme@gmail.com",
];
return $userModel->where([
"id" => 101,
])->set($data)->update();
We perform deletion from the database as follows:
$userModel = new UserModel();
return $userModel->where([
"id" => 101,
])->delete();
Search (sql like)
$builder->like('title', 'match');
// Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
More at
docs.
To get all the data from the database, we use:
$query = $builder->get(); // SELECT * FROM mytable
foreach ($query->getResult() as $row) {
echo $row->title; //show column "title"
}
Or if we need it for pagination:
$query = $builder->get(10, 20); // SELECT * FROM mytable LIMIT 20, 10