ThinkPHP 6.0 基础教程 - 增删改查

数据库

根目录下.example.env文件复制一下命名为.env内容如下:

APP_DEBUG = true

[APP]
DEFAULT_TIMEZONE = Asia/Shanghai

[DATABASE]
TYPE = mysql
HOSTNAME = 127.0.0.1
DATABASE = tp
USERNAME = root
PASSWORD = root
HOSTPORT = 3306
CHARSET = utf8
DEBUG = true

[LANG]
default_lang = zh-cn#语言

呐,这样你就成功连接数据库啦~!当然你也可以在config/database.php中去配置。

Migration 基础

执行命令行:

composer require topthink/think-migration

创建文件,注意:一定要用大驼峰写法

php think migrate:create ArticleTable

执行完成后,会在项目根目录多一个database目录,这里面存放类库操作文件.
编辑一下刚刚创建的文件

public function change()
{
    // create the table
    $table  =  $this->table('article');
    $table->addColumn('title', 'string', ['comment' => '文章标题'])
    ->addColumn('body', 'text', ['comment' => '文章内容'])
    ->addTimestamps()
    ->create();
}

继续执行命令行:

php think migrate:run

呐,灰常NB的在mysql里自动建立articles表与migrations表.注意migrations不要删除它是log不信你自己打开看看:laughing:

是的,没错!你也可以在小绿叶中自己手动创建表,lol

模型

执行命令:

php think make:model Article

app/model文件下自动建立Article Model类文件

Seed 生成测试数据

执行命令:

php think seed:create ArticleSeeder

编辑下database/seeds/ArticleSeeder文件

public function run()
{
    $data = [
        [
            'title' => '文章标题',
            'body' => '文章内容'
        ]
    ];

    $this->table('article')->insert($data)->saveData();
}

执行命令:

php think seed:run

本想用factory实现测试数据的,发现跑不通。:laughing:

View 层美化

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文章列表</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item active" aria-current="page">文章列表</li>
    </ol>
</nav>
<button type="button" class="btn btn-primary">新增</button>

<ul class="list-group">
    <li class="list-group-item">
        <a href="">Cras justo odio</a>
    </li>
</ul>
</body>
</html>

查询

路由

Route::get('article', 'article/index');

Article控制器中添加model方法

public function model()
{
    return new \app\model\Article();
}

Article控制器中在index方法

public function index()
{
    $data = $this->model()->select();

    return view('index', [
        'data'  => $data
    ]);
}

View

<div class="col-md-12" style="margin-top: 20px;">
    <ul class="list-group">
        {volist name="data" id='v' empty="暂时没有数据" }
        <li class="list-group-item">
            <a href="article/{$v.id}">{$v.title}</a>
        </li>
        {/volist}
    </ul>
</div>

效果

ThinkPHP 6.0 基础教程 - 增删改查

新增

路由

Route::get('article/create', 'article/create');

Route::post('article', 'article/save');

Article控制器中

public function create()
{
  return view('create');
}

public function save(Request $request)
{
    $request = $request->post();

    $this->model()->create($request);

    return redirect('article');
}

View层 新增create.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文章添加</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item active" aria-current="page">文章添加</li>
    </ol>
</nav>
<div class="col-md-12">
    <form method="post" action="/article" enctype="multipart/form-data">
        <div class="form-group">
            <label for="exampleInputTitle">Title address</label>
            <input type="text" name="title" class="form-control" id="exampleInputTitle">
        </div><div class="form-group">
        <label for="exampleInputBody">Body address</label>
        <textarea class="form-control" name="body" id="exampleInputBody" rows="3"></textarea>
    </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</div>
</body>
</html>

ThinkPHP 6.0 基础教程 - 增删改查

ThinkPHP 6.0 基础教程 - 增删改查

ThinkPHP 6.0 基础教程 - 增删改查

更新

路由

Route::get('article/<id>/edit', 'article/edit');

Route::put('article/<id>', 'article/update');

Article控制器中

public function edit($id)
{
    $data = $this->model()->findOrFail($id);

    return view('edit', [
        'data' => $data
    ]);
}

public function update(Request $request, $id)
{
    $request = $request->post();

    $this->model()->where('id', $id)->update($request);

    return redirect('/article');
}

View层 新增edit.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文章编辑</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
</head>
<body>
<nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item active" aria-current="page">文章编辑</li>
    </ol>
</nav>
<div class="col-md-12">
    <form method="post" action="/article/{$data.id}" enctype="multipart/form-data">
        <input type="hidden" name="_method" value="put">
        <div class="form-group">
            <label for="exampleInputTitle">Title address</label>
            <input type="text" name="title" class="form-control" value="{$data.title}" id="exampleInputTitle">
        </div>
        <div class="form-group">
            <label for="exampleInputBody">Body address</label>
            <textarea class="form-control" name="body" id="exampleInputBody" rows="3">{$data.body}</textarea>
        </div>
        <button type="submit" class="btn btn-primary">Submit</button>
    </form>
</div>
</body>
</html>

效果

ThinkPHP 6.0 基础教程 - 增删改查

ThinkPHP 6.0 基础教程 - 增删改查

删除

路由

Route::delete('article/<id>', 'article/delete');

Article控制器中

public function delete($id)
{
    $this->model()->where('id', $id)->delete();

    return redirect('/article');
}

View

// index.html
<a href="#" data-id="{$v.id}" type="button" class="btn btn-danger del" style="margin-right: 20px;">删除</a>
// js 删除逻辑
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.0/jquery.js"></script>
<script>
  $('.del').on('click',function (evt) {
  let url = 'article/'+$(this).data('id');
        let type = 'delete';
        let data = {id: $(this).data('id')};
        let self = $(this);
        $.ajax({
  url,
  type,
  data
  }).then(function (value) {
  var li = self.parents('li');
            li.remove();
        });
    })
</script>

效果

ThinkPHP 6.0 基础教程 - 增删改查


至此我们已经完成,tp6的基本操作~!

等等还有如果你感觉每一步操作都添加路由特麻烦的话,有个骚操作

Route::resource('article', 'article');

这样就路由就包含了增删改查不用每个都去写,验证一下
执行命令行

php think route:list

查看所有路由
ThinkPHP 6.0 基础教程 - 增删改查

ThinkPHP 6.0 基础教程 - 增删改查

本作品采用《CC 协议》,转载必须注明作者和本文链接
与其感慨路难行,不如马上出发。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!