独立使用Laravel的ORM
众所周知,laravel的ORM使用起来非常顺手,并且强大,那么如果我们不用laravel也想用ORM该怎么做了
1、composer 安装需要的组件
composer require illuminate/database
2、初始化组件,简单理解就是配置数据库的链接信息给ORM,将这个信息在入口文件处引入
<?php $database = [ 'driver' => 'mysql', 'host' => env('DB_HOST'), 'database' => env('DB_NAME'), 'username' => env('DB_USER'), 'password' => env('DB_PASSWORD'), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', ]; use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule; //创建一个数据库的链接 $capsule->addConnection($database); //静态可访问 $capsule->setAsGlobal(); //启动Eloquent,实际上就是解析链接信息,开始建立数据库的链接 $capsule->bootEloquent();
3、使用ORM
<?php namespace app\models; use Illuminate\Database\Eloquent\Model; class Orders extends Model { protected $table = 'orders'; }
3.1、使用DB
use Illuminate\Database\Capsule\Manager as DB; public function index() { DB::table('users')->where('id', 1)->first(); }