laravel orm独立使用

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,就基本足够了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值