CodeIgniter 데이터베이스: 설정, 업데이트 및 데이터 삭제

⚡ 스마트 요약

CodeIgniter Database는 연락처 관리자용 모델과 컨트롤러를 구축합니다. MySQL공유되는 기본 모델(BaseModel)은 삽입, 읽기, 업데이트 및 삭제 기능을 구현하고, 자식 모델인 친구(Pals)와 도시(Cities)는 이를 상속받으므로 컨트롤러는 애플리케이션 전체에서 동일한 데이터베이스 작업을 재사용할 수 있습니다.

  • 🗄️ 개요: 서로 연관된 두 테이블인 'pals'와 'cities'는 외래 키를 사용하여 일대일 관계를 모델링합니다.
  • ⚙️ 구성 : database.php 파일은 연결을 설정하고 데이터베이스 라이브러리를 로드합니다.
  • 🧬 기본 모델: 상위 모델은 get_all, get_by_id, get_where, insert, update 및 delete 메서드를 정의합니다.
  • 👨‍👩‍👧 계승: Pals와 Cities는 BaseModel을 상속하므로 해당 메서드를 재사용하고 필요한 경우 재정의합니다.
  • 🔗 조인: Pals 모델은 도시들을 연결하여 도시 이름과 연락처 정보를 함께 가져옵니다.
  • 🎛️ 컨트롤러 : 도시 및 연락처 컨트롤러는 모델, 양식 및 유효성 검사를 함께 연결합니다.
  • ♻️ 재사용 : 상속을 사용하면 반복적인 CRUD 코드를 제거하고 모델을 간결하게 유지할 수 있습니다.

Code이그나이터 데이터베이스

Code이그나이터 데이터베이스

이전 튜토리얼에서는 기본 사항을 다뤘습니다. CodeIgniter Active Record를 사용하여 데이터베이스에서 레코드를 삽입, 업데이트, 삭제 및 읽는 방법을 알아봅니다. 이 튜토리얼에서는 데이터베이스 모델을 생성하고 폼을 사용하여 데이터베이스 레코드를 생성하고 업데이트합니다. 데이터베이스 작업이 처음이신 분들도 이 튜토리얼을 통해 쉽게 이해할 수 있을 것입니다. Code이그나이터님, 다음 내용을 읽어보시기 바랍니다. 이전 튜토리얼 먼저.

CodeIgniter 데이터베이스 구성

먼저 튜토리얼 프로젝트의 데이터베이스를 생성하겠습니다. 연락처 정보를 관리하기 위한 간단한 데이터베이스를 만들 것이며, 'pals' 테이블과 'cities' 테이블, 이렇게 두 개의 테이블로 구성됩니다. 'pals' 테이블과 'cities' 테이블은 일대일 관계로, 'cities' 테이블의 'id'가 기본 키이고 'city_id'가 'pals' 테이블의 외래 키입니다.

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

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. 이 모델은 데이터 액세스, 데이터 조작 및 비즈니스 논리를 다룹니다.

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

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

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

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

Pals 및 Cities 모델을 포함한 BaseModel의 클래스 다이어그램

위 이미지에 설명된 대로 두 개의 모델을 생성하겠습니다. 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);
}
}

이리:

  • `protected $table = ”;`는 `table`이라는 이름의 protected 변수를 정의합니다. 이 변수는 해당 하위 클래스에서 기본 모델 메서드가 상호 작용해야 하는 테이블을 지정하기 위해 채워집니다.
  • `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_model.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_model extends BaseModel {…}`는 부모 모델인 `BaseModel`을 상속하며, 자식 클래스에서 부모 모델의 모든 메서드를 자동으로 사용할 수 있도록 합니다.
  • protected $table = 'pals';는 이 모델과 연결된 테이블 이름을 정의합니다.
  • __construct() {…}는 부모 생성자를 초기화합니다.
  • `public function get_by_id($id) {…}`는 `get_by_id` 메서드를 오버라이드하여 사용자 정의 구현을 제공합니다. 이 쿼리는 조인을 사용하여 `cities` 테이블에서 도시 이름을 검색합니다.
  • public function get_all() {…}는 pals 테이블과 cities 테이블 간의 조인 쿼리를 구현하기 위해 get_all을 재정의합니다.

application/models/Cities_model.php 경로에 새 파일을 생성하세요.

<?php
class Cities_model extends BaseModel {
protected $table = 'cities';

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

이리:

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

보시다시피, 상속은 모델 작업을 할 때 많은 시간을 절약해 줍니다. Code점화기.

연락처 관리자 컨트롤러

이제 모델을 만들었으니 애플리케이션의 컨트롤러를 만들어 보겠습니다. Cities와 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'));
}
}

이리:

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

application/controllers 폴더에 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'));
}
}

연락처 관리자 보기

우리는 이미 폼과 유효성 검사에 대해 살펴보았습니다. Code이전 튜토리얼에서 Igniter를 사용했으므로, 거기서 개발한 코드를 활용할 것입니다. 참고로, 애플리케이션의 화면은 다음과 같습니다.

연락처 관리자 보기

아래 링크를 클릭하면 뷰 코드를 다운로드할 수 있습니다.

CodeIgniter 연락처 관리자 보기 다운로드

자주 묻는 질문

기본 모델(BaseModel)은 공유되는 삽입, 읽기, 업데이트 및 삭제 메서드를 한 번만 보유합니다. 자식 모델은 이러한 메서드를 상속받고 다른 부분만 재정의하므로 중복을 제거하고 각 모델의 크기를 작게 유지할 수 있습니다.

각 연락처에는 도시 이름이 아닌 city_id가 저장됩니다. 이 오버라이드 코드는 cities 테이블을 조인하여 쿼리 결과가 각 연락처와 함께 읽기 쉬운 도시 이름으로 표시되도록 합니다.

컨트롤러는 모델을 로드하고, 제출된 폼을 검증하며, 데이터를 저장하고 리디렉션하거나 오류와 함께 폼을 다시 로드합니다. 또한 모델, 뷰, 유효성 검사 라이브러리를 연결합니다.

네. 테이블 정의를 기반으로 AI는 CRUD 메서드가 포함된 기본 모델과 테이블당 하나의 자식 모델을 생성하고, 외래 키에 읽기 쉬운 레이블이 필요한 경우 조인 오버라이드를 추가할 수 있습니다. Rev생성된 조인을 확인하세요.

데이터베이스 라이브러리는 원시 쿼리 및 Active Record 메서드를 제공합니다. 모델은 이러한 호출을 특정 테이블에 대한 의미 있고 재사용 가능한 작업으로 래핑합니다.ping 컨트롤러 외부로의 데이터 접근.

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