2019年12月26日09:43:14
github:https://github.com/illuminate/database
為什么要獨立使用這個orm,有以下幾個原因
第一:功能實在太強大,寫起來舒服,代碼復用好
第二:性能不錯
Laravel支持四個數據庫: MySQL 5.6+(版本政策) PostgreSQL 9.4+(版本政策) SQLite 3.8.8以上 SQL Server 2017+(版本政策)
目前已經配套到laravel 6.x,目前需要php7.2以上
隨便找個文件夾執行
composer require illuminate/database
在引入到你需要使用的文件里面
官方使用說明:
用於PHP的完整數據庫工具包,提供了表達性查詢構建器,ActiveRecord樣式ORM和模式構建器。目前,它支持MySQL,Postgres,SQL Server和SQLite。它還充當Laravel PHP框架的數據庫層。
使用說明
首先,創建一個新的“膠囊”管理器實例。Capsule的目的是使配置庫盡可能容易地在Laravel框架之外使用。
use Illuminate\Database\Capsule\Manager as Capsule; $capsule = new Capsule; $capsule->addConnection([ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => 'password', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ]); // Set the event dispatcher used by Eloquent models... (optional) use Illuminate\Events\Dispatcher; use Illuminate\Container\Container; $capsule->setEventDispatcher(new Dispatcher(new Container)); // Make this Capsule instance available globally via static methods... (optional) $capsule->setAsGlobal(); // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher()) $capsule->bootEloquent(); composer require "illuminate/events" required when you need to use observers with Eloquent.
一旦注冊了Capsule實例。您可以這樣使用它:
使用查詢生成器
$users = Capsule::table('users')->where('votes', '>', 100)->get(); 可以從Capsule直接訪問其他核心方法,方法與從DB Facade相同: $results = Capsule::select('select * from users where id = ?', [1]); 使用架構生成器 Capsule::schema()->create('users', function ($table) { $table->increments('id'); $table->string('email')->unique(); $table->timestamps(); }); 使用 Eloquent ORM class User extends Illuminate\Database\Eloquent\Model {} $users = User::where('votes', '>', 1)->get();
demo
include __DIR__ . '/vendor/autoload.php'; include_once __DIR__ . '/Model/User.php'; $database = [ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'test', 'username' => 'root', 'password' => 'root', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ]; use Illuminate\Container\Container; use Illuminate\Database\Capsule\Manager as Capsule; use app\models\User; $capsule = new Capsule; // 創建鏈接 $capsule->addConnection($database); // 設置全局靜態可訪問 $capsule->setAsGlobal(); // 啟動Eloquent $capsule->bootEloquent(); //$user = Capsule::table('user')->get(); $user = User::get()->toArray(); print_r($user);
注意官方的demo不能直接運行的,需要修改一下
如果在實際項目中運行在加入一個自動加載的class,就基本足夠了