sirakoff/mongodb

基于 MongoDB 的 Laravel 4 Eloquent 模型和查询构建器

维护者

详细信息

github.com/sirakov/mongodb

来源

安装: 11

依赖: 0

建议者: 0

安全: 0

星级: 1

关注者: 2

Forks: 1,424

v2.0.2 2014-09-16 10:50 UTC

README

Latest Stable Version Total Downloads Build Status Coverage Status

一个支持 MongoDB 的 Eloquent 模型和查询构建器,使用原始 Laravel API。 此库扩展了原始 Laravel 类,因此使用完全相同的方法。

从 v1 升级到 v2

在这个新版本中,嵌入式文档不再使用带前导下划线的属性保存到父模型。如果您有一个类似 embedsMany('Book') 的关系,这些书籍现在存储在 $model['books'] 下,而不是 $model['_books']。这样改变是为了让嵌入式关系对新手开发者来说不那么令人困惑。

如果您想升级到这个新版本而不必更改所有现有的数据库对象,您可以修改您的嵌入式关系以使用包含下划线的非默认本地键

$this->embedsMany('Book', '_books');

https://github.com/jenssegers/laravel-mongodb/releases/tag/v2.0.0 阅读完整的变更日志

安装

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

将包添加到您的 composer.json 并运行 composer update

{
    "require": {
        "jenssegers/mongodb": "*"
    }
}

app/config/app.php 中添加服务提供程序

'Jenssegers\Mongodb\MongodbServiceProvider',

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

配置

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

'default' => 'mongodb',

并添加一个新的 mongodb 连接

'mongodb' => array(
    'driver'   => 'mongodb',
    'host'     => 'localhost',
    'port'     => 27017,
    'username' => 'username',
    'password' => 'password',
    'database' => 'database'
),

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

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

Eloquent

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

use Jenssegers\Mongodb\Model as Eloquent;

class User extends Eloquent {}

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

use Jenssegers\Mongodb\Model as Eloquent;

class User extends Eloquent {

    protected $collection = 'users_collection';

}

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

use Jenssegers\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'       => 'Jenssegers\Mongodb\Model',

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

class MyModel extends Moloquent {}

查询构建器

数据库驱动程序直接连接到原始查询构建器。当使用 mongodb 连接时,您将能够构建流畅的查询以执行数据库操作。为了方便起见,还有一个 collection 别名用于 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 的原生身份验证功能,请注册此包含的服务提供程序

'Jenssegers\Mongodb\Auth\ReminderServiceProvider',

此服务提供程序将稍微修改内部 DatabaseReminderRepository 以添加基于 MongoDB 的密码提醒支持。如果您不使用密码提醒,您无需注册此服务提供程序,其他所有内容应该都可以正常工作。

Sentry

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

会话

MongoDB 会话驱动程序在单独的包中可用,请查看 https://github.com/jenssegers/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() 的第二个参数必须是 Illuminate\Database\Query\Grammars\Grammar 的实例,但给定的是 null

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

use Jenssegers\Mongodb\Model as Eloquent;

class User extends Eloquent {

    protected $connection = 'mongodb';

}

示例

基本用法

检索所有模型

$users = User::all();

通过主键检索记录

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

Wheres

$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();

偏移量 & 限制

$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 Jenssegers\Mongodb\Eloquent\SoftDeletingTrait;

class User extends Eloquent {

    use SoftDeletingTrait;

    protected $dates = ['deleted_at'];

}

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

MongoDB 特定操作符

存在

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

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

全部

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

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

大小

选择数组字段为指定大小的文档。

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

正则表达式

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

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();

类型

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

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

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

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

条件

匹配满足 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/jenssegers/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 Jenssegers\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 Jenssegers\Mongodb\Model as Eloquent;

class User extends Eloquent {

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

}

以及反向关联

use Jenssegers\Mongodb\Model as Eloquent;

class Item extends Eloquent {

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

}

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

use Jenssegers\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 Jenssegers\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');

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

  • 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();

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

EmbedsOne 关系

embedsOne 关系类似于 EmbedsMany 关系,但它只嵌入单个模型。

use Jenssegers\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 模型需要扩展 Jenssegers\Eloquent\Model。请注意,此功能仅适用于 hasOne、hasMany 和 belongsTo 关系。

示例 SQL 基于用户模型

use Jenssegers\Eloquent\Model as Eloquent;

class User extends Eloquent {

    protected $connection = 'mysql';

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

}

以及 MongoDB 基于消息模型

use Jenssegers\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();

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