symfomany/laravel-mongo

为 Laravel 5 设计的基于 MongoDB 的 Eloquent 模型和查询构建器

1.0 2016-01-07 18:06 UTC

This package is not auto-updated.

Last update: 2024-09-18 17:45:10 UTC


README

Build Status Packagist Packagist Packagist Packagist

通过 Composer 安装

composer require symfomany/laravel-mongo

MongoDB PHP 项目

针对 PHP7 和 MongoDB 驱动程序的 Mongo/laravel-mongodb 的 适配 https://github.com/Mongo/laravel-mongodb

规格

  • Eloquant ORM 和查询构建器到 Laravel 5 的桥梁

需求

  • Laravel 5 的 Illuminate 查询构建器
  • Eloquent ORM
  • mongodb/mongodb

目标 & 进化

探索 API MongoDB 来扩展原生功能

  • 数据库信息
  • 批量
  • DeleteMany
  • Delete
  • FindAndModify
  • FindAndDelete
  • InsertMany
  • Agregate: 创建命令 & 执行
  • DeleteResult / InsertManyResult /InsertOneResult / UpdateResult

适配器

第一部分:MongoDB

连接(选项)

  • collection() table()
  • getCollection()
  • getSchemaBuilder()
  • getMongoClient() => Client
  • getMongoDB() => db
  • createConnection() / getDriverName()
  • getDsn()
  • disconnect()

集合(连接/集合 MongoDB 驱动程序)

  • __call() => 调用驱动程序的原生方法 + 处理日志

构建器(连接 + 查询处理器)

  • 运算符 => 可用子句运算符

  • 转换 => 运算符转换。= > < !=

  • project() => 投影

  • timeout() => 最大延迟

  • hint() => 请求中特殊索引

  • find($id, $columns) => 包含输出列的 ID

  • get($columns) => 返回除了条件列之外的所有内容

  • getFresh() alias de get() => 输出列

  • generateCacheKey()

  • aggregate()

  • exists() => 如果查询中存在任何结果

  • distinct() => 强制查询仅返回不同的结果。

  • orderBy() => 在查询中添加排序和方向

  • whereBetween() => 一个带有 ...AND.. 的 where Between

  • forPage($page) => 限制和偏移量用于一个页面,具有 skip 和 take

  • insert(array) => 插入 + 批量插入

  • insertGetId() => 插入并返回插入的 ID

  • update($values) => 修改

  • increment($column) => 增加一列

  • decrement($column) => 减少一列

  • delete($id)

  • from()

  • truncate()

  • lists() => 获取一个包含给定列值的数组。

  • raw() => 评估一个表达式

  • push() => 将一个或多个值追加到数组中

  • pull() => 从数组中删除一个或多个值

  • drop() => 删除一个或多个字段。

  • newQuery() => 查询构建器的新实例。(子查询)

  • convertKey() => ???

  • where()

  • compileWheres() => 转换关键词 + id + AND|OR + 递归 where

  • compileWhereBasic() => Like +Regexp +not +

  • compileWhereNested() + compileWhereIn() + compileWhereNotIn()() + compileWhereNull() + compileWhereNotNull() + compileWhereBetween() + compileWhereRaw()

  • 注意:集合必须具有 Eloquant 方法或 BaseCollection(抽象)

第二部分:Eloquant ORM

构建器

集合

SchemaBuilder(带有连接)

  • hasTable() / hasCollection() / hasColumns()
  • create() / drop()

目录

安装

请确保您已安装MongoDB PHP驱动程序。您可以在以下位置找到安装说明:https://php.ac.cn/manual/en/mongo.installation.php

对于Laravel 5,使用composer安装最新稳定版本

composer require symfomany/laravel-mongo

版本兼容性

并在config/app.php中添加服务提供者

Mongo\Mongodb\MongodbServiceProvider::class,

对于与Lumen一起使用,请在bootstrap/app.php中添加服务提供者。在此文件中,您还需要启用Eloquent。但是,您必须确保对$app->withEloquent();的调用在注册了MongodbServiceProvider之后

$app->register('Mongo\Mongodb\MongodbServiceProvider');

$app->withEloquent();

服务提供者将向原始数据库管理器注册mongodb数据库扩展。无需注册额外的外观或对象。当使用mongodb连接时,Laravel将自动为您提供相应的mongodb对象。

对于Laravel之外的使用,请查看Capsule管理器并添加

$capsule->getDatabaseManager()->extend('mongodb', function($config)
{
    return new Mongo\Mongodb\Connection($config);
});

配置

app/config/database.php中更改默认数据库连接名称

'default' => env('DB_CONNECTION', 'mongodb'),

并添加一个新的mongodb连接

'mongodb' => array(
    'driver'   => 'mongodb',
    'host'     => env('DB_HOST', 'localhost'),
    'port'     => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE', ''),
    'username' => env('DB_USERNAME', ''),
    'password' => env('DB_PASSWORD', ''),
    'options' => array(
        'db' => 'admin' // sets the authentication database required by mongo 3
    )
),

您可以使用以下配置连接到多个服务器或复制集

'mongodb' => array(
    'driver'   => 'mongodb',
    'host'     => array('server1', 'server2'),
    'port'     => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE', ''),
    'username' => env('DB_USERNAME', ''),
    'password' => env('DB_PASSWORD', ''),
    'options'  => array('replicaSet' => 'replicaSetName')
),

Eloquent

此包包括一个启用MongoDB的Eloquent类,您可以使用它来为相应的集合定义模型。

use Mongo\Mongodb\Model as Eloquent;

class User extends Eloquent {}

注意,我们没有告诉Eloquent应该使用哪个集合为User模型。就像原始Eloquent一样,除非明确指定,否则类的小写复数名称将用作表名。您可以通过在模型上定义collection属性来指定自定义集合(表的别名)

use Mongo\Mongodb\Model as Eloquent;

class User extends Eloquent {

    protected $collection = 'users_collection';

}

注意: Eloquent还将假设每个集合都有一个名为id的主键列。您可以通过定义primaryKey属性来覆盖此约定。同样,您可以通过定义connection属性来覆盖在利用模型时应使用的数据库连接的名称。

use Mongo\Mongodb\Model as Eloquent;

class MyModel extends Eloquent {

    protected $connection = 'mongodb';

}

其余部分与原始Eloquent模型的工作方式相同。有关Eloquent的更多信息,请参阅https://laravel.net.cn/docs/eloquent

可选:别名

您还可以通过在app/config/app.php中的别名数组中添加以下内容来注册MongoDB模型的别名

'Moloquent'       => 'Mongo\Mongodb\Model',

这将允许您像以下这样使用已注册的别名

class MyModel extends Moloquent {}

查询构建器

数据库驱动程序直接连接到原始查询构建器。当使用mongodb连接时,您将能够构建流畅的查询以执行数据库操作。为了方便起见,除了table的别名之外,还有一些额外的mongodb特定运算符/操作。

$users = DB::collection('users')->get();

$user = DB::collection('users')->where('name', 'John')->first();

如果您没有更改默认数据库连接,您在查询时需要指定它。

$user = DB::connection('mongodb')->collection('users')->get();

有关查询构建器的更多信息,请参阅https://laravel.net.cn/docs/queries

模式

数据库驱动程序还具有(有限)的架构构建器支持。您可以轻松操作集合并设置索引

Schema::create('users', function($collection)
{
    $collection->index('name');

    $collection->unique('email');
});

支持的运算包括

  • 创建和删除
  • 集合
  • hasCollection
  • 索引和删除索引(支持复合索引)
  • 唯一
  • 背景、稀疏、过期(MongoDB特定)

所有其他(不受支持)操作都作为虚拟透传方法实现,因为MongoDB不使用预定义的架构。有关架构构建器的更多信息,请参阅https://laravel.net.cn/docs/schema

扩展

身份验证

如果您想使用Laravel的本地身份验证功能,请注册此包含的服务提供者

'Mongo\Mongodb\Auth\PasswordResetServiceProvider',

此服务提供者将稍微修改内部DatabaseReminderRepository以添加基于MongoDB的密码提醒支持。如果您不使用密码提醒,您不需要注册此服务提供者,其他一切应该都能正常工作。

Sentry

如果您想将此库与Sentry一起使用,请查看https://github.com/Mongo/Laravel-MongoDB-Sentry

会话

MongoDB会话驱动器可在单独的包中找到,请查看https://github.com/Mongo/Laravel-MongoDB-Session

故障排除

在...中找不到类'MongoClient'

MongoClient类是MongoDB PHP驱动程序的一部分。通常,此错误表示您忘记安装,或没有正确安装此驱动程序。您可以在https://php.ac.cn/manual/en/mongo.installation.php找到此驱动程序的安装说明。

要检查您是否已正确安装驱动程序,请运行以下命令

$ php -i | grep 'Mongo'
MongoDB Support => enabled

传递给Illuminate\Database\Query\Builder::__construct()的参数2必须是Illuminate\Database\Query\Grammars\Grammar的实例,但提供了null

要解决这个问题,您需要检查两件事。首先检查您的模型是否扩展了正确的类;这个类应该是Mongo\Mongodb\Model。其次,检查您的模型是否使用了MongoDB连接。如果您没有更改数据库配置文件中的默认数据库连接,您需要指定MongoDB启用连接。如果您没有设置别名并更改默认数据库连接,您的类应该如下所示

use Mongo\Mongodb\Model as Eloquent;

class User extends Eloquent {

    protected $connection = 'mongodb';

}

示例

基本用法

检索所有模型

$users = User::all();

通过主键检索记录

$user = User::find('517c43667db388101e00000f');

Where

$users = User::where('votes', '>', 100)->take(10)->get();

Or语句

$users = User::where('votes', '>', 100)->orWhere('name', 'John')->get();

And语句

$users = User::where('votes', '>', 100)->where('name', '=', 'John')->get();

使用数组中的Where In

$users = User::whereIn('age', array(16, 18, 20))->get();

当使用whereNotIn时,如果字段不存在,将返回对象。结合使用whereNotNull('age')来排除这些文档。

使用Where Between

$users = User::whereBetween('votes', array(1, 100))->get();

Where null

$users = User::whereNull('updated_at')->get();

OrderBy

$users = User::orderBy('name', 'desc')->get();

Offset & Limit

$users = User::skip(10)->take(5)->get();

Distinct

Distinct需要返回唯一值的字段。

$users = User::distinct()->get(array('name'));
// or
$users = User::distinct('name')->get();

Distinct可以与where结合使用

$users = User::where('active', true)->distinct('name')->get();

高级Wheres

$users = User::where('name', '=', 'John')->orWhere(function($query)
    {
        $query->where('votes', '>', 100)
              ->where('title', '<>', 'Admin');
    })
    ->get();

Group By

未分组的所选列将使用$last函数进行聚合。

$users = Users::groupBy('title')->get(array('title', 'name'));

聚合

聚合仅适用于MongoDB版本大于2.2。

$total = Order::count();
$price = Order::max('price');
$price = Order::min('price');
$price = Order::avg('price');
$total = Order::sum('price');

聚合可以与where结合使用

$sold = Orders::where('sold', true)->sum('price');

Like

$user = Comment::where('body', 'like', '%spam%')->get();

增加或减少列的值

对指定属性执行递增或递减操作(默认为1)

User::where('name', 'John Doe')->increment('age');
User::where('name', 'Jaques')->decrement('weight', 50);

返回更新的对象数

$count = User->increment('age');

您还可以指定要更新的其他列

User::where('age', '29')->increment('age', 1, array('group' => 'thirty something'));
User::where('bmi', 30)->decrement('bmi', 1, array('category' => 'overweight'));

软删除

当软删除模型时,实际上并不会从您的数据库中删除。相反,在记录上设置一个deleted_at时间戳。要为模型启用软删除,将SoftDeletingTrait应用到模型上

use Mongo\Mongodb\Eloquent\SoftDeletes;

class User extends Eloquent {

    use SoftDeletes;

    protected $dates = ['deleted_at'];

}

有关更多信息,请查看https://laravel.net.cn/docs/eloquent#soft-deleting

MongoDB特定运算符

Exists

匹配具有指定字段的文档。

User::where('age', 'exists', true)->get();

All

匹配包含查询中指定所有元素的数组。

User::where('roles', 'all', array('moderator', 'author'))->get();

Size

如果数组字段是指定的大小,则选择文档。

User::where('tags', 'size', 3)->get();

Regex

选择与指定正则表达式匹配的值的文档。

User::where('name', 'regex', new MongoRegex("/.*doe/i"))->get();

注意:您还可以使用Laravel正则表达式操作。这些操作更灵活,并将自动将您的正则表达式字符串转换为MongoRegex对象。

User::where('name', 'regexp', '/.*doe/i'))->get();

及其逆

User::where('name', 'not regexp', '/.*doe/i'))->get();

Type

如果字段是指定的类型,则选择文档。有关更多信息,请查看:http://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type

User::where('age', 'type', 2)->get();

Mod

对字段值执行模运算并选择具有指定结果的文档。

User::where('age', 'mod', array(10, 0))->get();

Where

匹配满足JavaScript表达式的文档。更多信息请查看 http://docs.mongodb.org/manual/reference/operator/query/where/#op._S_where

插入、更新和删除

插入、更新和删除记录的操作与原始Eloquent相同。

保存新的模型

$user = new User;
$user->name = 'John';
$user->save();

您还可以使用create方法在一行中保存新的模型。

User::create(array('name' => 'John'));

更新模型

要更新模型,您可以检索它,更改属性,并使用save方法。

$user = User::first();
$user->email = 'john@foo.com';
$user->save();

还支持upsert操作,请查看 https://github.com/Mongo/laravel-mongodb#mongodb-specific-operations

删除模型

要删除模型,只需在实例上调用delete方法。

$user = User::first();
$user->delete();

或者通过其键删除模型

User::destroy('517c43667db388101e00000f');

有关模型操作的更多信息,请查看 https://laravel.net.cn/docs/eloquent#insert-update-delete

日期

Eloquent允许您使用Carbon/DateTime对象而不是MongoDate对象。内部,这些日期将在保存到数据库时转换为MongoDate对象。如果您想在非默认日期字段上使用此功能,您需要手动指定,具体请参阅此处: https://laravel.net.cn/docs/eloquent#date-mutators

示例

use Mongo\Mongodb\Model as Eloquent;

class User extends Eloquent {

    protected $dates = array('birthday');

}

这允许您执行以下查询

$users = User::where('birthday', '>', new DateTime('-18 years'))->get();

关系

支持的关系有

  • hasOne
  • hasMany
  • belongsTo
  • belongsToMany

示例

use Mongo\Mongodb\Model as Eloquent;

class User extends Eloquent {

    public function items()
    {
        return $this->hasMany('Item');
    }

}

以及反向关系

use Mongo\Mongodb\Model as Eloquent;

class Item extends Eloquent {

    public function user()
    {
        return $this->belongsTo('User');
    }

}

belongsToMany关系不会使用一个“联合”表,而是将id推送到related_ids属性中。这使得belongsToMany方法的第二个参数变得无用。如果您想为关系定义自定义键,请将其设置为null

use Mongo\Mongodb\Model as Eloquent;

class User extends Eloquent {

    public function groups()
    {
        return $this->belongsToMany('Group', null, 'users', 'groups');
    }

}

其他关系目前尚不支持,但将来可能添加。有关这些关系的更多信息,请参阅 https://laravel.net.cn/docs/eloquent#relationships

EmbedsMany关系

如果您想嵌入模型而不是引用它们,可以使用embedsMany关系。这个关系与hasMany关系类似,但将模型嵌入到父对象中。

use Mongo\Mongodb\Model as Eloquent;

class User extends Eloquent {

    public function books()
    {
        return $this->embedsMany('Book');
    }

}

您可以通过动态属性访问嵌入的模型

$books = User::first()->books;

反向关系会自动生成,您不需要定义这个反向关系。

$user = $book->user;

插入和更新嵌入的模型的工作方式与hasMany关系类似

$book = new Book(array('title' => 'A Game of Thrones'));

$user = User::first();

$book = $user->books()->save($book);
// or
$book = $user->books()->create(array('title' => 'A Game of Thrones'))

您可以使用嵌入模型的save方法(自2.0.0版本以来可用)来更新嵌入的模型

$book = $user->books()->first();

$book->title = 'A Game of Thrones';

$book->save();

您可以通过在关系上使用destroy方法或在模型上使用delete方法(自2.0.0版本以来可用)来删除嵌入的模型

$book = $user->books()->first();

$book->delete();
// or
$user->books()->destroy($book);

如果您想在不接触数据库的情况下添加或删除嵌入的模型,可以使用associatedissociate方法。要将更改最终写入数据库,请保存父对象

$user->books()->associate($book);

$user->save();

与其他关系一样,embedsMany根据模型名称假设关系的本地键。您可以通过向embedsMany方法传递第二个参数来覆盖默认的本地键

return $this->embedsMany('Book', 'local_key');

嵌入的关系将返回一个包含嵌入项的集合,而不是查询构建器。为了允许更查询-like的行为,使用了一个修改后的Collection类,支持以下附加操作

  • where($key, $operator, $value)
  • whereIn($key, $values) 和 whereNotIn($key, $values)
  • whereBetween($key, $values) 和 whereNotBetween($key, $values)
  • whereNull($key) 和 whereNotNull($key)
  • orderBy($key, $direction)
  • oldest() 和 latest()
  • limit($value)
  • offset($value)
  • skip($value)

这允许您在集合结果上执行简单的查询

$books = $user->books()->where('rating', '>', 5)->orderBy('title')->get();

注意:因为嵌入的模型不存储在单独的集合中,所以您不能查询所有嵌入的模型。您始终必须通过父模型访问它们。

嵌套One关系

嵌套One关系类似于嵌套Many关系,但仅嵌入单个模型。

use Mongo\Mongodb\Model as Eloquent;

class Book extends Eloquent {

    public function author()
    {
        return $this->embedsOne('Author');
    }

}

您可以通过动态属性访问嵌入的模型

$author = Book::first()->author;

插入和更新嵌入式模型的工作方式与hasOne关系相似

$author = new Author(array('name' => 'John Doe'));

$book = Books::first();

$author = $book->author()->save($author);
// or
$author = $book->author()->create(array('name' => 'John Doe'));

您可以使用save方法更新嵌入式模型(自2.0.0版本以来可用)

$author = $book->author;

$author->name = 'Jane Doe';
$author->save();

您可以这样替换嵌入式模型为新模型

$newAuthor = new Author(array('name' => 'Jane Doe'));
$book->author()->save($newAuthor);

MySQL关系

如果您正在使用混合MongoDB和SQL设置,那么您很幸运!模型将根据相关模型的类型自动返回MongoDB或SQL关系。当然,如果希望此功能双向工作,则SQL模型需要扩展Mongo\Eloquent\Model。请注意,此功能仅适用于hasOne、hasMany和belongsTo关系。

示例SQL-based用户模型

use Mongo\Eloquent\Model as Eloquent;

class User extends Eloquent {

    protected $connection = 'mysql';

    public function messages()
    {
        return $this->hasMany('Message');
    }

}

以及MongoDB-based消息模型

use Mongo\Mongodb\Model as Eloquent;

class Message extends Eloquent {

    protected $connection = 'mongodb';

    public function user()
    {
        return $this->belongsTo('User');
    }

}

原始表达式

这些表达式将直接注入到查询中。

User::whereRaw(array('age' => array('$gt' => 30, '$lt' => 40)))->get();

您还可以在内部MongoCollection对象上执行原始表达式。如果在模型类上执行,它将返回模型集合。如果在查询构建器上执行,它将返回原始响应。

// Returns a collection of User models.
$models = User::raw(function($collection)
{
    return $collection->find();
});

// Returns the original MongoCursor.
$cursor = DB::collection('users')->raw(function($collection)
{
    return $collection->find();
});

可选:如果不传递闭包给原始方法,则内部MongoCollection对象可访问

$model = User::raw()->findOne(array('age' => array('$lt' => 18)));

内部MongoClient和MongoDB对象可以像这样访问

$client = DB::getMongoClient();
$db = DB::getMongoDB();

MongoDB特定操作

游标超时

为防止MongoCursorTimeout异常,您可以手动设置应用于游标的超时值

DB::collection('users')->timeout(-1)->get();

Upsert

更新或插入文档。更新方法的附加选项将直接传递给原生更新方法。

DB::collection('users')->where('name', 'John')
                       ->update($data, array('upsert' => true));

投影

您可以使用project方法对查询应用投影。

DB::collection('items')->project(array('tags' => array('$slice' => 1)))->get();

带分页的投影

$limit = 25;
$projections = array('id', 'name');
DB::collection('items')->paginate($limit, $projections);

Push

向数组添加项目。

DB::collection('users')->where('name', 'John')->push('items', 'boots');
DB::collection('users')->where('name', 'John')->push('messages', array('from' => 'Jane Doe', 'message' => 'Hi John'));

如果您不希望有重复的项目,将第三个参数设置为true

DB::collection('users')->where('name', 'John')->push('items', 'boots', true);

Pull

从数组中删除项目。

DB::collection('users')->where('name', 'John')->pull('items', 'boots');
DB::collection('users')->where('name', 'John')->pull('messages', array('from' => 'Jane Doe', 'message' => 'Hi John'));

Unset

从文档中删除一个或多个字段。

DB::collection('users')->where('name', 'John')->unset('note');

您还可以在模型上执行unset。

$user = User::where('name', 'John')->first();
$user->unset('note');

查询缓存

您可以使用remember方法轻松缓存查询的结果

$users = User::remember(10)->get();

来源:https://laravel.net.cn/docs/queries#caching-queries

查询记录

默认情况下,Laravel会记录当前请求中已运行的所有查询。然而,在某些情况下,例如在插入大量行时,这可能导致应用程序使用过多的内存。要禁用日志,可以使用disableQueryLog方法

DB::connection()->disableQueryLog();

来源:https://laravel.net.cn/docs/database#query-logging