非 Laravel 项目使用 Eloquent

什么是 Eloquent ?

Eloquent ORM 提供了漂亮、简洁的 ActiveRecord 实现来和数据库交互。每个数据库表都有一个对应的”模型“用来与该表交互。你可以通过模型查询数据表中的数据,并将新记录添加到数据表中。

Eloquent 使用方法

安装 Eloquent

使用 Composer 来安装

1
composer require illuminate/database

配置数据库连接

新建 bootstrap.php,内容如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?php

require __DIR__.'/../vendor/autoload.php';

use Illuminate\Database\Capsule\Manager as Capsule;

$capsule = new Capsule;

$capsule->addConnection([
    "driver" => "mysql",
    "host" => "127.0.0.1",
    "database" => "test",
    "username" => "root",
    "password" => "root",
    'charset' => "utf8mb4",
    'collation' => "utf8mb4_general_ci"
]);

$capsule->setAsGlobal();
$capsule->bootEloquent();

创建表 Migration

新建 migrate-comments.php

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

require "../bootstrap.php";

use Illuminate\Database\Capsule\Manager as Capsule;

Capsule::schema()->create('comments', function ($table) {
       $table->increments('id');
       $table->string('nickname');
       $table->string('content');
       $table->timestamps();
   });

访问 migrate-comments.php 进行迁移

新建 Model

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

require "../bootstrap.php";

use Illuminate\Database\Eloquent\Model as Eloquent;

class CommentsModel extends Eloquent
{
    protected $table='comments';
    public $primaryKey = 'id';
    public $timestamps = true;
}

添加数据

1
2
3
4
5
6
<?php

$commentsModel = new CommentsModel();
$commentsModel->nickname = $request['nickname'];
$commentsModel->content = $request['content'];
$commentsModel->save();

这里实现了简单的示例,更多特性还需看 Laravel Eloquent 文档。

updatedupdated2020-08-112020-08-11
Load Comments?