CodeIgniter_05_Model

本文详细介绍了CodeIgniter框架中数据库的连接、查询、插入和删除操作,包括传统结构和查询构造器模式的使用。同时,展示了如何创建和使用模型来简化数据库交互,包括模型的配置、查找、保存和删除数据的方法。此外,还提及了数据验证的重要性和基本规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Model Part_1

Notes:A introduction of traditional structures and query builder pattern will be demonstrated followed by a deeper study into model.

1.work with database

1.1 simple examples

1.1.1 getDataBaseConnection

As you can see,\config\DataBase provides cleaner and automatic method to access database.

//\config\DataBase.php
    public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'bob',
        'password' => '123456',
        'database' => 'demo1',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];
   //Notes:environment:development

/controller/dbexample.php:get connection between database and Codeigniter.

$conn = \Config\Database::connect();
1.1.2 Query

There are`two way designated to retrieve data:traditional structure(array &&object version) and query builder pattern(object version only).

a.traditional structure
//array version
$sql = 'SELECT * FROM table_name' //LIMIT 1;
$query = $conn->query($sql);
$results=$query->getResultArray(); //if single  result : getRowArray()
//Access Element Format:$result['post_id'];
//object version
$sql ='SELECT post_id,post_title,post_content FROM  table_name';
$query=$conn->query($sql);
$results=$query->getResult();//if single element:getRow()
//Access element format:$result->post_id;
b.query builder pattern
$results = $conn->table('table_name')->get();
//disadvantage:return all the row it retrieves
1.1.3 Insert

specification:illustrate all feasible cases here.

//traditional structures
$sql = " INSERT INTO table_name (row1_name,row2_name)  VALUES (".$conn->escape($parameter01).",". $conn->escape($parameter2). ) ";
$conn->query($sql);
echo $conn->affectedRows();
//query builder pattern
$data=[
           'row1_name'=>'value01',
           'row2_name'=>'value02'
           ];
$query=$conn->table('table_name')->insert($data);
1.1.4 some problems
1./ verus \

URL:/
FIle Address:(Library)

2.cannot transfer a sub-result of result from getResult() to another php file called by view_cell()

The rules we need to follow:
within view tier: key => value

superior level $data=[‘key’=>‘value’];// $data is transferred to the inderior level
inferior level: $key //rule of getting value

within controller tier: whatever especially object or array

3.php basic knowledge

access non-static element: -> eg: $ this->result; //variable
access static element: :: eg: $ this::$data //variable

$thisself$parent
a pointer to the current classjust represent this classparent class
this is like a instance of class,so it cannot access static propertiesself is just a duplicate thing as same as the original calss,so it can access static properties.In fact,it also can access non-static properties by useing instace

1.2 database configuration

CodeIgniter has a config file that lets you store your database connection values (username, password, database name, etc.). The config file is located at app/Config/Database.php. You can also set database connection values in the .env file. See below for more details.
/.env

1.2.1 \ config\database.php
public $default = [
        'DSN'      => '',
        'hostname' => '',
        'username' => '',
        'password' => '',
        'database' => '',
        'DBDriver' => '',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

Reference

1.2.2 config .env file

remove all the setting in \config\database.php to reset it to default version.This is because .env makes use of its prperties.
(only for maysql case)
default group name:

database.default.username = 'root';
database.default.password = '';
database.default.database = 'ci4';

explanation for parameters:
Reference

Model Part_2

1.Codeigniter Model

specification:codeigniter provides a convenient way to connect and manipulate database.

1.1 create our model

At first we need to specify one database restored in variable ‘$table’ .A default database will be used defined in .env file.

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table      = 'users';
    protected $primaryKey = 'id';

    protected $useAutoIncrement = true;

    protected $returnType     = 'array';
    //three parameters:
    //1.array 2.object 3.fully qualified name of a class :getCustomResultObject()
    
    protected $useSoftDeletes = true;

    protected $allowedFields = ['name', 'email'];

    protected $useTimestamps = false;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    protected $validationRules    = [];
    protected $validationMessages = [];
    protected $skipValidation     = false;
}

1.2 model operation

1.2.1 find data(select)
//find()
$user =$userModel->find(1);
$users = $userModel->find([1,2,3]);

//findColumn():find where this column is
$user = $userModel->findColumn($column_name);

//findAll():returns all results:
$users = $userModel->where('active', 1)  ->findAll();
$user =$userModel->findall();
$users = $userModel->findAll($limit, $offset);

//........reference loading

1.2.2 save data(insert,update)
//insert
$data = [
    'username' => 'darth',
    'email'    => 'd.vader@theempire.com',
];

$userModel->insert($data);

//update
$data = [
    'username' => 'darth',
    'email'    => 'd.vader@theempire.com',
];

$userModel->update($id, $data);
//$id-> **IMPORTANT** primary  key


//second  approach Insert
$data = [
    'active' => 1,
];

$userModel->update([1, 2, 3], $data);

//a flexible approach update
$userModel
    ->whereIn('id', [1,2,3])  //find
    ->set(['active' => 1])    //update
    ->update();



// Defined as a model property
$primaryKey = 'id';

// Does an insert()
$data = [
    'username' => 'darth',
    'email'    => 'd.vader@theempire.com',
];

$userModel->save($data);

// Performs an update, since the primary key, 'id', is found.
$data = [
    'id'       => 3,
    'username' => 'darth',
    'email'    => 'd.vader@theempire.com',
];
$userModel->save($data);
1.2.3 delete data(delete)
$userModel->delete(12);
$userModel->where('id', 12)->delete();
$userModel->purgeDeleted();//permanently removing all rows that have ‘deleted_at IS NOT NULL’.

2.validation

specification:validation means that it makes sure all values make sense.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值