CodeIgniter 데이터베이스: 데이터 구성, 편집, 업데이트, 삭제

코드이그나이터 데이터베이스

이전 튜토리얼에서는 CodeIgniter 활성 레코드의 기본 사항과 데이터베이스에서 레코드를 삽입, 업데이트, 삭제 및 읽는 방법을 다루었습니다. 이 자습서에서는 데이터베이스 모델을 만들고 양식을 사용하여 데이터베이스 레코드를 만들고 업데이트합니다. CodeIgniter에서 데이터베이스 작업을 처음 접하는 경우 이전 튜토리얼을 읽는 것이 좋습니다.

Codeigniter 데이터베이스 구성

튜토리얼 프로젝트 데이터베이스를 만드는 것으로 시작하겠습니다. 연락처 정보를 관리하기 위한 간단한 데이터베이스를 만들 것입니다. pals라는 이름과 그들이 사는 cities라는 두 개(2)의 테이블이 있는 간단한 데이터베이스를 만들 것입니다. pals와 cities 간의 관계는 일대일 관계이며 cities의 id는 기본 키이고 pals 테이블의 city_id는 외래 ​​키입니다.

다음 스크립트를 실행하여 데이터베이스를 생성하세요.

CREATE TABLE `pals` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `city_id` int(11) DEFAULT NULL,
  `contact_name` varchar(245) DEFAULT NULL,
  `contact_number` varchar(245) DEFAULT NULL,
  `email_address` varchar(245) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

이제 도시 테이블을 만들어 보겠습니다.

CREATE TABLE `cities` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(245) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ;

CodeIgniter 데이터베이스 모델

이제 데이터베이스에 대한 모델을 생성하겠습니다. 모델은 M 부분입니다. MVC. 이 모델은 데이터 액세스, 데이터 조작 및 비즈니스 논리를 다룹니다.

CodeIgniter에서 각 모델은 지원할 메서드를 정의해야 합니다. 각 모델에서 동일한 코드를 반복하는 대신 객체 지향 프로그래밍의 상속을 활용하고 모델이 지원하기를 원하는 기본 메서드를 정의하는 상위 모델 클래스를 만듭니다.

아래 표에는 정의할 메서드와 데이터에 액세스하는 방법이 나와 있습니다.

S / N 방법 기술설명
1 __건설하다 상위 생성자 메서드를 호출하는 생성자 메서드를 정의합니다.
2 모든 것을 가져라 조건 없이 데이터베이스에서 모든 필드와 레코드를 검색합니다.
3 get_by_id id라는 INT 유형의 기본 키를 사용하여 데이터베이스에서 단일 행을 검색합니다.
4 get_where 기준에 따라 데이터베이스에서 모든 필드를 검색합니다.
5 삽입하다 데이터베이스에 새 레코드를 삽입합니다.
6 최신 정보 id라는 INT 유형의 기본 키를 기반으로 기존 데이터베이스 레코드를 업데이트합니다.
7 삭제 id라는 INT 유형의 기본 키를 기반으로 데이터베이스에서 기존 레코드를 삭제합니다.

다음 이미지는 클래스 다이어그램과 Pals와 Cities 자식 모델이 부모 모델 BaseModel과 어떻게 관련되어 있는지 보여줍니다.

CodeIgniter 데이터베이스 모델

위 이미지에 설명된 대로 두 가지 모델을 생성하겠습니다.

application/models/BaseModel.php에서 새로운 클래스 BaseModel을 생성합니다.

다음 코드를 추가하세요

<?php

class BaseModel extends CI_Model {

    protected $table = '';

    public function __construct() {
        parent::__construct();
    }

    public function get_all() {
        return $this->db->get($this->table)
                        ->result();
    }

    public function get_by_id($id) {
        return $this->db->get_where($this->table, array('id' => $id))
                        ->row();
    }

    public function get_where($where) {
        return $this->db->where($where)
                        ->get($this->table)
                        ->result();
    }

    public function insert($data) {
        return $this->db->insert($this->table, $data);
    }

    public function update($id, $data) {
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id) {
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }
}

이리,

  • 보호된 $table = ”; table이라는 보호 변수를 정의합니다. 이는 기본 모델 클래스 메서드가 상호 작용해야 하는 테이블을 지정하기 위해 해당 하위 클래스로 채워집니다.
  • public function __construct() {…}는 생성자 메서드를 정의하고 상위 클래스 CI_Model의 생성자 메서드를 실행합니다.
  • get_all() {…}는 데이터베이스 라이브러리와 $table 변수의 값을 사용하여 데이터베이스에 대해 SELECT 쿼리를 실행합니다.
  • get_by_id($id) {…}는 데이터베이스에서 단일 행을 검색하는 방법을 정의하고 INT 데이터 유형이어야 하는 매개변수 $id를 허용합니다.
  • get_where($where) {…}는 where 절을 설정할 수 있는 get 메소드를 정의합니다.
  • insert($data) {…}는 삽입 메소드를 정의하고 데이터베이스에 기록될 값이 포함된 배열 매개변수 $data를 허용합니다.
  • update($id, $data) {…}는 업데이트 방법을 정의하고 데이터베이스에서 업데이트할 값이 포함된 배열 매개변수 $data를 허용합니다.
  • delete($id) {…}는 INT 데이터 유형이어야 하는 $id 매개변수를 허용하는 삭제 메소드를 정의합니다.

이제 상위 모델 클래스 작업이 완료되었으므로 Pals 모델을 만들어 보겠습니다.

application/models/Pals.php에 새 파일을 만듭니다.

다음 코드를 추가하세요

<?php

class Pals_model extends BaseModel {

    protected $table = 'pals';

    public function __construct() {
        parent::__construct();
    }

    public function get_by_id($id) {
        $this->db->where('pals.id', $id);
        $this->db->select('pals.*,cities.name');
        $this->db->from('pals');
        $this->db->join('cities', 'pals.city_id = cities.id');
        $query = $this->db->get();
        return $query->row();
    }

    public function get_all() {
        $this->db->select('pals.*,cities.name');
        $this->db->from('pals');
        $this->db->join('cities', 'pals.city_id = cities.id');
        $query = $this->db->get();
        return $query->result();
    }
}

이리,

  • class Pals는 BaseModel을 확장합니다. {...}는 상위 모델인 BaseModel을 확장하고 BaseModel에 정의된 모든 메소드를 자동으로 하위 클래스에 액세스하도록 만듭니다.
  • 보호된 $table = '친구'; 상위 모델과 연관된 테이블 이름을 정의합니다.
  • __construct() {…}는 상위 생성자를 초기화합니다.
  • public function get_by_id($id) {…}는 get_by_id를 재정의하여 Pals 모델에 특정한 사용자 정의 구현을 제공합니다. get_by_id에 대한 쿼리는 조인을 사용하여 도시 테이블에서 도시 이름을 검색합니다.
  • public function get_all() {…}은 get_all 메서드를 재정의하여 pals와 도시 테이블 간의 조인 쿼리를 구현합니다.

application/models/Cities.php에 새 파일을 생성합니다.

<?php
class Cities extends BaseModel {
    protected $table = 'cities';
    
    public function __construct() {
        parent::__construct();
    }
}

이리,

보호된 $table = '도시'; 모델 데이터베이스 테이블을 정의합니다.

위에 제공된 코드에서 볼 수 있듯이 상속은 CodeIgniter에서 모델을 작업할 때 많은 시간을 절약해 줍니다. 다음 섹션에서는

연락처 관리자 컨트롤러

이제 모델을 만들었으므로 애플리케이션용 컨트롤러를 만들어 보겠습니다. Contacts와 Cities라는 두 개의 컨트롤러가 있습니다.

도시부터 시작해보자

application/controllers 디렉토리에 Cities.php라는 새 파일을 생성합니다.

다음 코드를 추가하세요

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Cities extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url', 'form');
        $this->load->library('form_validation');
        $this->load->model('cities_model');
    }

    public function index() {
        $header['title'] = 'Cities Listing';
        $data['pals'] = $this->cities_model->get_all();

        $this->load->view('header',$header);
        $this->load->view('cities/index', $data);
        $this->load->view('footer');
    }

    public function create() {
        $header['title'] = 'Create City';
        
        $this->load->view('header',$header);
        $this->load->view('cities/create');
        $this->load->view('footer');
    }

    public function store() {
        $rules = array(
            array(
                'field' => 'name',
                'label' => 'City Name',
                'rules' => 'required'
            )
        );

        $this->form_validation->set_rules($rules);

        if ($this->form_validation->run() == TRUE) {
            $data = array('name' => $this->input->post('name'));
            $this->cities_model->insert($data);

            redirect(base_url('cities'));
        } else {
            $header['title'] = 'Create City';
            
            $this->load->view('header',$header);
            $this->load->view('cities/create');
            $this->load->view('footer');
        }
    }

    public function edit($id) {
        $header['title'] = 'Edit City';
        $data['city'] = $this->cities_model->get_by_id($id);

        $this->load->view('header', $header);
        $this->load->view('cities/edit', $data);
        $this->load->view('footer');
    }

    public function update($id) {
        $rules = array(
            array(
                'field' => 'name',
                'label' => 'City Name',
                'rules' => 'required'
            )
        );

        $this->form_validation->set_rules($rules);

        if ($this->form_validation->run() == TRUE) {
            $data = array('name' => $this->input->post('name'));
            $this->cities_model->update($id,$data);

            redirect(base_url('cities'));
        } else {
            $header['title'] = 'Edit City';
            $data['city'] = $this->cities_model->get_by_id($id);
            
            $this->load->view('header',$header);
            $this->load->view('cities/create',$data);
            $this->load->view('footer');
        }
    }

    public function delete($id) {
        $header['title'] = 'Delete City';
        $data['city'] = $this->cities_model->get_by_id($id);

        $this->load->view('header', $header);
        $this->load->view('cities/delete', $data);
        $this->load->view('footer');
    }

    public function destroy($id) {
        $this->cities_model->delete($id);

        redirect(base_url('cities'));
    }
}

이리,

위의 코드는 데이터베이스에서 행을 생성, 업데이트, 삭제 및 읽는 데 필요한 모든 메서드를 구현합니다.

응용 프로그램/컨트롤러에 다른 파일 Contacts.php를 만듭니다.

다음 코드를 추가하세요

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Contacts extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->helper('url', 'form');
        $this->load->library('form_validation');
        $this->load->model('pals_model');
    }

    public function index() {
        $header['title'] = 'Contacts List';
        $data['pals'] = $this->pals_model->get_all();

        $this->load->view('header', $header);
        $this->load->view('contacts/index', $data);
        $this->load->view('footer');
    }

    public function create() {
        $this->load->model('cities_model');
        $header['title'] = 'Create Contact';
        $data['cities'] = $this->cities_model->get_all();

        $this->load->view('header', $header);
        $this->load->view('contacts/create', $data);
        $this->load->view('footer');
    }

    public function store() {
        $rules = array(
            array(
                'field' => 'contact_name',
                'label' => 'Contact Name',
                'rules' => 'required'
            ),
            array(
                'field' => 'contact_number',
                'label' => 'Contact Number',
                'rules' => 'required',
                'errors' => array(
                    'required' => 'You must provide a %s.',
                ),
            ),
            array(
                'field' => 'email_address',
                'label' => 'Email Address',
                'rules' => 'required'
            ),
            array(
                'field' => 'city_id',
                'label' => 'City',
                'rules' => 'required'
            )
        );

        $this->form_validation->set_rules($rules);

        if ($this->form_validation->run() == FALSE) {
            $this->load->model('cities_model');
            $header['title'] = 'Create Contact';
            $data['cities'] = $this->cities_model->get_all();

            $this->load->view('header', $header);
            $this->load->view('contacts/create', $data);
            $this->load->view('footer');
        } else {
            $data = array(
                'city_id' => $this->input->post('city_id'),
                'contact_name' => $this->input->post('contact_name'),
                'contact_number' => $this->input->post('contact_number'),
                'email_address' => $this->input->post('email_address'),
            );

            $this->pals_model->insert($data);

            redirect(base_url('contacts'));
        }
    }

    public function edit($id) {
        $this->load->model('cities_model');
        $header['title'] = 'Edit Contact';
        $data['cities'] = $this->cities_model->get_all();

        $data['pal'] = $this->pals_model->get_by_id($id);
 
        $this->load->view('header', $header);
        $this->load->view('contacts/edit', $data);
        $this->load->view('footer');
    }

    public function update($id) {
        $rules = array(
            array(
                'field' => 'contact_name',
                'label' => 'Contact Name',
                'rules' => 'required'
            ),
            array(
                'field' => 'contact_number',
                'label' => 'Contact Number',
                'rules' => 'required',
                'errors' => array(
                    'required' => 'You must provide a %s.',
                ),
            ),
            array(
                'field' => 'email_address',
                'label' => 'Email Address',
                'rules' => 'required'
            ),
            array(
                'field' => 'city_id',
                'label' => 'City',
                'rules' => 'required'
            )
        );

        $this->form_validation->set_rules($rules);

        if ($this->form_validation->run() == FALSE) {
            $this->load->model('cities_model');
            $header['title'] = 'Create Contact';
            $data['cities'] = $this->cities_model->get_all();

            $data['pal'] = $this->pals_model->get_by_id($id);

            $this->load->view('header', $header);
            $this->load->view('contacts/edit', $data);
            $this->load->view('footer');
        } else {
            $data = array(
                'city_id' => $this->input->post('city_id'),
                'contact_name' => $this->input->post('contact_name'),
                'contact_number' => $this->input->post('contact_number'),
                'email_address' => $this->input->post('email_address'),
            );

            $this->pals_model->update($id, $data);

            redirect(base_url('contacts'));
        }
    }

    public function delete($id) {
        $this->load->model('cities_model');
        $header['title'] = 'Delete Contact';
        $data['cities'] = $this->cities_model->get_all();

        $data['pal'] = $this->pals_model->get_by_id($id);

        $this->load->view('header',$header);
        $this->load->view('contacts/delete',$data);
        $this->load->view('footer');
    }
    
    public function destroy($id){
        $this->pals_model->delete($id);
        
        redirect(base_url('contacts'));
    }
}

연락처 관리자 보기

우리는 이전 튜토리얼에서 CodeIgniter의 양식과 유효성 검사를 이미 살펴보았습니다. 이전 튜토리얼에서 개발한 코드를 사용하겠습니다. 완벽함을 위해 이전 튜토리얼에서 생성한 코드를 재현하겠습니다.

우리 응용 프로그램의 견해는 다음과 같습니다

연락처 관리자 보기

아래 링크를 클릭하면 위 보기에 대한 코드를 다운로드할 수 있습니다.

CodeIgniter 연락처 관리자 조회수 다운로드

제품 개요

이 튜토리얼에서는 다음에서 모델을 생성하는 방법을 배웁니다. CodeIgniter. 우리는 객체 지향 프로그래밍의 상속을 활용하여 삽입, 읽기, 업데이트, 삭제라는 4가지 주요 데이터베이스 작업을 구현하는 기본 모델을 만들어 코드 재사용성을 촉진했습니다.

우리는 실제적인 응용 프로그램을 사용하여 개념을 보여주었으며, 다음 튜토리얼에서는 응용 프로그램에 더 많은 기능을 추가하여 계속해서 보여드리겠습니다.

이 게시물을 요약하면 다음과 같습니다.