Codeigniter 4基础教程(6)-- Model部分

本节课讲演示一个Model

0.新建数据表
仍然使用之前的codeigniter4数据库,并且需要修改对应的app/Config/Database.php。数据表的内容如下:

CREATE TABLE `posts` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `banner` varchar(255) NOT NULL,
 `title` varchar(255) NOT NULL,
 `intro` varchar(255) NOT NULL,
 `content` varchar(255) NOT NULL,
 `category` int(255) NOT NULL,
 `tags` varchar(255) NOT NULL,
 `created_at` date NOT NULL,
 `created_by` int(11) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8

此时的表给没有任何内容。

1.新建PostsModel.php文件
app/Models/PostsModel.php

<?php

	namespace App\Models;
	use CodeIgniter\Model;

	class PostsModel extends Model{
    
    

		protected $table = 'posts';
		protected $primaryKey = 'id';
		protected $returnType = 'array';
		protected $useSoftDeletes = true;

		protected $allowedFields = ['banner','title','intro','content','category','tags','created_at','created_by'];

	}
	?>

看名称就能猜得出需要设置的内容,表名,主键,返回类型,软删除以及允许修改的字段名称,还有其他的一些内容请查看官方文档。

2.修改Dashboard.php
app/Controllers/Dashboard.php

<?php namespace App\Controllers;

use CodeIgniter\Controller;
use App\Models\UsersModel;
use App\Models\PostsModel;

class Dashboard extends BaseController
{
    
    
	public function index()
	{
    
    

		$model = new PostsModel();
		$model->insert([
			"banner"=>'img1.png',
			"title"=>"My first post",
			"intro"=>"Hello this is me",
			"content"=>"Lorem ispsum bababa",
			"category"=>"1",
			"tages"=>"sports",
			"created_at"=>date("Y-m-d"),
			"created_by"=>"1"
			]);
	}
}

3.查看结果
浏览器输入http://ci4.net/Dashboard,多回车几次,
打开localhost/phpmyadmin查看数据,插入成功。
在这里插入图片描述
4.【补充】另一个写法
标准的写法是继承自Model,另外一个做法是放在controller中,

$db = \Config\Database::connect();
$db->escape($sql);
$db->query("select * from users")->getResult();

这里和标准的PHP中Mysqli的差别很小。

$db = $this->db->table('users');
$data = $db->get()->getResult();
$data = $db->select('id','name')->where('id',1)->get();
$data = $db->select('id','name')->whereIn('id',array(1,3,5,7,9))->get();

齐活。

猜你喜欢

转载自blog.csdn.net/yaoguoxing/article/details/106600607