convenia/laravel-mongodb

基于MongoDB的Eloquent模型和查询构建器,适用于Laravel(Moloquent)

v1.0.0 2023-06-14 19:55 UTC

This package is auto-updated.

Last update: 2024-09-14 22:56:31 UTC


README

此包为MongoDB的Eloquent模型和查询构建器添加功能,使用原始的Laravel API。此库扩展了原始的Laravel类,因此使用完全相同的方法。

安装

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

Laravel版本兼容性

通过Composer安装此包

$ composer require convenia/laravel-mongodb

Laravel

如果您的Laravel版本没有自动加载包,请将服务提供者添加到config/app.php

Convenia\Mongodb\MongodbServiceProvider::class,

Lumen

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

$app->register(Convenia\Mongodb\MongodbServiceProvider::class);

$app->withEloquent();

服务提供者将向原始数据库管理器注册MongoDB数据库扩展。无需注册额外的外观或对象。

当使用MongoDB连接时,Laravel会自动为您提供相应的MongoDB对象。

非Laravel项目

对于Laravel之外的使用,请参阅Capsule manager并添加

$capsule->getDatabaseManager()->extend('mongodb', function($config, $name) {
    $config['name'] = $name;

    return new Convenia\Mongodb\Connection($config);
});

测试

要为此包运行测试,请运行

docker-compose up

数据库测试

要每次测试后重置数据库,请添加

use Illuminate\Foundation\Testing\DatabaseMigrations;

同样,在测试类内部添加

use DatabaseMigrations;

请注意,这些特性目前尚不支持

  • use Database Transactions;
  • use RefreshDatabase;

配置

要配置新的MongoDB连接,请向config/database.php添加新的连接条目

'mongodb' => [
    'driver' => 'mongodb',
    'dsn' => env('DB_DSN'),
    'database' => env('DB_DATABASE', 'homestead'),
],

dsn键包含用于连接到您的MongoDB部署的连接字符串。格式和可用选项在MongoDB文档中有所说明。

除了使用连接字符串之外,您还可以使用hostport配置选项来创建连接字符串。

'mongodb' => [
    'driver' => 'mongodb',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', 27017),
    'database' => env('DB_DATABASE', 'homestead'),
    'username' => env('DB_USERNAME', 'homestead'),
    'password' => env('DB_PASSWORD', 'secret'),
    'options' => [
        'appname' => 'homestead',
    ],
],

连接配置中的options键对应于uriOptions参数

Eloquent

扩展基础模型

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

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    //
}

与普通模型一样,MongoDB模型类会根据模型名称知道使用哪个集合。对于Book,将使用集合books

要更改集合,传递$collection属性。

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    protected $collection = 'my_books_collection';
}

注意: MongoDB文档会自动存储一个唯一的ID,该ID存储在_id属性中。如果您想使用自己的ID,则替换$primaryKey属性,并将其设置为您的自己的主键属性名称。

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    protected $primaryKey = 'id';
}

// MongoDB will also create _id, but the 'id' property will be used for primary key actions like find().
Book::create(['id' => 1, 'title' => 'The Fault in Our Stars']);

同样,您可以定义一个connection属性来覆盖使用模型时应使用的数据库连接名称。

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    protected $connection = 'mongodb';
}

扩展Authenticatable基模型

此包包含一个MongoDB Authenticatable Eloquent类Convenia\Mongodb\Auth\User,您可以使用它来替换默认的Authenticatable类Illuminate\Foundation\Auth\User,以用于您的User模型。

use Convenia\Mongodb\Auth\User as Authenticatable;

class User extends Authenticatable
{

}

软删除

当软删除模型时,它实际上并没有从您的数据库中删除。相反,会在记录上设置deleted_at时间戳。

要为模型启用软删除,请将Convenia\Mongodb\Eloquent\SoftDeletes特质应用到模型上。

use Convenia\Mongodb\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;
}

有关更多信息,请查看Laravel关于软删除的文档

保护属性

在选择保护属性或标记某些属性为可填充时,Taylor Otwell更喜欢填充路径。这基于此处描述的最近的安全问题

请注意,保护仍然有效,但您可能会遇到意外的行为。

日期

Eloquent允许您使用Carbon或DateTime对象而不是MongoDate对象。内部,这些日期在保存到数据库时将被转换为MongoDate对象。

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    protected $casts = ['birthday' => 'datetime'];
}

这允许您执行如下查询

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

基本用法

检索所有模型

$users = User::all();

根据主键检索记录

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

Where

$posts =
    Post::where('author.name', 'John')
        ->take(10)
        ->get();

OR语句

$posts =
    Post::where('votes', '>', 0)
        ->orWhere('is_approved', true)
        ->get();

AND语句

$users =
    User::where('age', '>', 18)
        ->where('name', '!=', 'John')
        ->get();

whereIn

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

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

whereBetween

$posts = Post::whereBetween('votes', [1, 100])->get();

whereNull

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

whereDate

$users = User::whereDate('birthday', '2021-5-12')->get();

用法与whereMonth / whereDay / whereYear / whereTime相同

高级Where

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

orderBy

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

Offset & Limit(跳过 & 拿取)

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

groupBy

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

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

Distinct

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

$users = User::distinct()->get(['name']);

// Equivalent to:
$users = User::distinct('name')->get();

Distinct可以与where结合使用

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

Like

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

聚合

聚合仅适用于MongoDB版本大于2.2.x

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

聚合可以与where结合使用

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

聚合也可以用于子文档

$total = Order::max('suborder.price');

注意:此聚合仅适用于单个子文档(如EmbedsOne),不适用于子文档数组(如EmbedsMany)。

增加/减少列的值

对指定的属性执行增量或减量(默认为1)

Cat::where('name', 'Kitty')->increment('age');

Car::where('name', 'Toyota')->decrement('weight', 50);

返回更新的对象数量

$count = User::increment('age');

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

Cat::where('age', 3)
    ->increment('age', 1, ['group' => 'Kitty Club']);

Car::where('weight', 300)
    ->decrement('weight', 100, ['latest_change' => 'carbon fiber']);

MongoDB特定运算符

Exists

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

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

All

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

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

Size

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

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

Regex

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

use MongoDB\BSON\Regex;

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

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

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', [10, 0])->get();

MongoDB特定地理空间运算

Near

$bars = Bar::where('location', 'near', [
    '$geometry' => [
        'type' => 'Point',
        'coordinates' => [
            -0.1367563, // longitude
            51.5100913, // latitude
        ],
    ],
    '$maxDistance' => 50,
])->get();

GeoWithin

$bars = Bar::where('location', 'geoWithin', [
    '$geometry' => [
        'type' => 'Polygon',
        'coordinates' => [
            [
                [-0.1450383, 51.5069158],
                [-0.1367563, 51.5100913],
                [-0.1270247, 51.5013233],
                [-0.1450383, 51.5069158],
            ],
        ],
    ],
])->get();

GeoIntersects

$bars = Bar::where('location', 'geoIntersects', [
    '$geometry' => [
        'type' => 'LineString',
        'coordinates' => [
            [-0.144044, 51.515215],
            [-0.129545, 51.507864],
        ],
    ],
])->get();

GeoNear

您可以在mongoDB上执行geoNear查询。您不需要在模型上指定自动字段。返回的实例是一个集合。因此,您可以执行集合操作。只需确保您的模型有一个location字段,并且有一个2dsphereIndex。在location字段中的数据必须保存为GeoJSON格式。location点必须以几何计算的WGS84参考系保存。这意味着,基本上,您需要按顺序保存经度和纬度,并且要计算距离找到近的点,您需要以相同的方式进行。

Bar::find("63a0cd574d08564f330ceae2")->update(
    [
        'location' => [
            'type' => 'Point',
            'coordinates' => [
                -0.1367563,
                51.5100913
            ]
        ]
    ]
);
$bars = Bar::raw(function ($collection) {
    return $collection->aggregate([
        [
            '$geoNear' => [
                "near" => [ "type" =>  "Point", "coordinates" =>  [-0.132239, 51.511874] ],
                "distanceField" =>  "dist.calculated",
                "minDistance" =>  0,
                "maxDistance" =>  6000,
                "includeLocs" =>  "dist.location",
                "spherical" =>  true,
            ]
        ]
    ]);
});

插入、更新和删除

插入、更新和删除记录的工作方式与原始的Eloquent相同。请参阅Laravel 文档的 Eloquent 部分

这里只指定了MongoDB特定的操作。

MongoDB特定操作

原始表达式

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

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

User::whereRaw([
    '$where' => '/.*123.*/.test(this.field)',
])->get();

User::whereRaw([
    '$where' => '/.*123.*/.test(this["hyphenated-field"])',
])->get();

您还可以对内部MongoCollection对象执行原始表达式。如果这在模型类上执行,它将返回一个模型集合。

如果这在查询构建器上执行,它将返回原始响应。

光标超时

为了防止MongoCursorTimeout异常,您可以手动设置一个将应用于光标的超时值

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

Upsert

更新或插入一个文档。更新方法的其他选项将直接传递给原生更新方法。

// Query Builder
DB::collection('users')
    ->where('name', 'John')
    ->update($data, ['upsert' => true]);

// Eloquent
$user->update($data, ['upsert' => true]);

投影

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

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

DB::collection('items')
    ->project(['tags' => ['$slice' => [3, 7]]])
    ->get();

带分页的投影

$limit = 25;
$projections = ['id', 'name'];

DB::collection('items')
    ->paginate($limit, $projections);

Push

向数组添加项目。

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

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

$user->push('messages', [
    'from' => 'Jane Doe',
    'message' => 'Hi John',
]);

如果您不想重复项目,将第三个参数设置为true

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

$user->push('items', 'boots', true);

Pull

从数组中删除一个项目。

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

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

$user->pull('messages', [
    'from' => 'Jane Doe',
    'message' => 'Hi John',
]);

Unset

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

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

$user->unset('note');

关系

基本用法

仅有的可用关系是

  • hasOne
  • hasMany
  • belongsTo
  • belongsToMany

MongoDB特定的关系是

  • embedsOne
  • embedsMany

这里有一个小例子

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    public function items()
    {
        return $this->hasMany(Item::class);
    }
}

hasMany的反向关系是belongsTo

use Convenia\Mongodb\Eloquent\Model;

class Item extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

belongsToMany和pivot

belongsToMany关系将不会使用“枢纽”表,而是将id推送到一个related_ids属性。这使得belongsToMany方法的第二个参数变得无意义。

如果您想为关系定义自定义键,将其设置为null

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    public function groups()
    {
        return $this->belongsToMany(
            Group::class, null, 'user_ids', 'group_ids'
        );
    }
}

EmbedsMany关系

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

记住:这些关系返回Eloquent集合,它们不返回查询构建器对象!

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    public function books()
    {
        return $this->embedsMany(Book::class);
    }
}

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

$user = User::first();

foreach ($user->books as $book) {
    //
}

反向关系自动可用。您不需要定义这个反向关系。

$book = Book::first();

$user = $book->user;

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

$book = $user->books()->save(
    new Book(['title' => 'A Game of Thrones'])
);

// or
$book =
    $user->books()
         ->create(['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->delete();

// Similar operation
$user->books()->destroy($book);

如果您想在不接触数据库的情况下添加或删除嵌入的模型,可以使用associatedissociate方法。

要将更改最终写入数据库,请保存父对象

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

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

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    public function books()
    {
        return $this->embedsMany(Book::class, 'local_key');
    }
}

嵌入式关系将返回嵌入式项的集合,而不是查询构建器。请在此处查看可用操作:https://laravel.net.cn/docs/master/collections

EmbedsOne关系

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

use Convenia\Mongodb\Eloquent\Model;

class Book extends Model
{
    public function author()
    {
        return $this->embedsOne(Author::class);
    }
}

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

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

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

$author = $book->author()->save(
    new Author(['name' => 'John Doe'])
);

// Similar
$author =
    $book->author()
         ->create(['name' => 'John Doe']);

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

$author = $book->author;

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

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

$newAuthor = new Author(['name' => 'Jane Doe']);

$book->author()->save($newAuthor);

查询构建器

基本用法

数据库驱动程序直接连接到原始查询构建器。

当使用 MongoDB 连接时,您将能够构建流畅的查询以执行数据库操作。

为了方便起见,还有一个 collection 别名用于 table,以及一些额外的 MongoDB 特定运算符/操作。

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

$hungerGames =
    DB::collection('books')
        ->where('name', 'Hunger Games')
        ->first();

如果您熟悉 Eloquent 查询,则具有相同的功能。

可用操作

要查看可用操作,请查看 Eloquent 部分。

事务

事务需要 MongoDB 版本 ^4.0 以及副本集或分片集群的部署。您可以在 MongoDB 文档中找到更多信息 在此处

基本用法

DB::transaction(function () {
    User::create(['name' => 'john', 'age' => 19, 'title' => 'admin', 'email' => 'john@example.com']);
    DB::collection('users')->where('name', 'john')->update(['age' => 20]);
    DB::collection('users')->where('name', 'john')->delete();
});
// begin a transaction
DB::beginTransaction();
User::create(['name' => 'john', 'age' => 19, 'title' => 'admin', 'email' => 'john@example.com']);
DB::collection('users')->where('name', 'john')->update(['age' => 20]);
DB::collection('users')->where('name', 'john')->delete();

// commit changes
DB::commit();

要取消事务,可以在事务期间的任何时刻调用 rollBack 方法

DB::beginTransaction();
User::create(['name' => 'john', 'age' => 19, 'title' => 'admin', 'email' => 'john@example.com']);

// Abort the transaction, discarding any data created as part of it
DB::rollBack();

注意: MongoDB 中的事务不能嵌套。DB::beginTransaction() 函数将在新创建或现有会话中启动新事务,并在事务已存在时引发 RuntimeException。更多详情请参阅 MongoDB 官方文档 事务和会话

DB::beginTransaction();
User::create(['name' => 'john', 'age' => 20, 'title' => 'admin']);

// This call to start a nested transaction will raise a RuntimeException
DB::beginTransaction();
DB::collection('users')->where('name', 'john')->update(['age' => 20]);
DB::commit();
DB::rollBack();

模式

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

基本用法

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

您还可以将 MongoDB 文档中指定的所有参数 传递给 $options 参数

Schema::create('users', function ($collection) {
    $collection->index(
        'username',
        null,
        null,
        [
            'sparse' => true,
            'unique' => true,
            'background' => true,
        ]
    );
});

继承的操作

  • 创建和删除
  • 集合
  • hasCollection
  • 索引和删除索引(支持复合索引)
  • 唯一

MongoDB特定操作

  • 后台
  • 稀疏
  • 过期
  • 地理空间

所有其他(不受支持)操作都作为虚拟透传方法实现,因为 MongoDB 不使用预定义的模式。

有关模式构建器的更多信息,请参阅 Laravel 文档

地理空间索引

地理空间索引对于查询基于位置的文档很有用。

它们有两种形式:2d2dsphere。使用模式构建器将这些添加到集合中。

Schema::create('bars', function ($collection) {
    $collection->geospatial('location', '2d');
});

要添加 2dsphere 索引

Schema::create('bars', function ($collection) {
    $collection->geospatial('location', '2dsphere');
});

扩展

跨数据库关系

如果您使用的是混合 MongoDB 和 SQL 设置,则可以在它们之间定义关系。

模型将根据相关模型类型自动返回 MongoDB 相关或 SQL 相关的关系。

如果您想双向使用此功能,则您的 SQL 模型需要使用 Convenia\Mongodb\Eloquent\HybridRelations 特性。

此功能仅适用于 hasOnehasManybelongsTo

MySQL 模型应使用 HybridRelations 特性

use Convenia\Mongodb\Eloquent\HybridRelations;

class User extends Model
{
    use HybridRelations;

    protected $connection = 'mysql';

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

在您的 MongoDB 模型中,您应定义关系

use Convenia\Mongodb\Eloquent\Model;

class Message extends Model
{
    protected $connection = 'mongodb';

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

身份验证

如果您想使用 Laravel 的原生认证功能,请注册此包含的服务提供程序

Convenia\Mongodb\Auth\PasswordResetServiceProvider::class,

此服务提供程序将略微修改内部 DatabaseReminderRepository 以添加对基于 MongoDB 的密码提醒的支持。

如果您不使用密码提醒,则不需要注册此服务提供程序,其他所有内容都应该正常工作。

队列

如果您想将 MongoDB 作为数据库后端,请在 config/queue.php 中更改驱动程序

'connections' => [
    'database' => [
        'driver' => 'mongodb',
        // You can also specify your jobs specific database created on config/database.php
        'connection' => 'mongodb-job',
        'table' => 'jobs',
        'queue' => 'default',
        'expire' => 60,
    ],
],

如果您想使用 MongoDB 处理失败的任务,请在 config/queue.php 中更改数据库

'failed' => [
    'driver' => 'mongodb',
    // You can also specify your jobs specific database created on config/database.php
    'database' => 'mongodb-job',
    'table' => 'failed_jobs',
],

Laravel特定

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

Convenia\Mongodb\MongodbQueueServiceProvider::class,

Lumen特定

使用 Lumen,请在 bootstrap/app.php 中添加服务提供者。然而,您必须确保在添加 MongodbServiceProvider 注册之后添加以下内容。

$app->make('queue');

$app->register(Convenia\Mongodb\MongodbQueueServiceProvider::class);

升级

从版本2升级到3

在这个新的大版本中,我们支持新的 MongoDB PHP 扩展,并且移动了 Model 类的位置,用特性替换了 MySQL 模型类。

请将所有 Convenia\Mongodb\Model 引用更改为 Convenia\Mongodb\Eloquent\Model,无论是在您的模型文件顶部还是在注册的别名中。

use Convenia\Mongodb\Eloquent\Model;

class User extends Model
{
    //
}

如果您使用混合关系,您的 MySQL 类现在应该扩展原始的 Eloquent 模型类 Illuminate\Database\Eloquent\Model 而不是已删除的 Convenia\Eloquent\Model

而是使用新的 Convenia\Mongodb\Eloquent\HybridRelations 特性。这应该会使事情更清晰,因为在这个包中只有一个单独的模型类。

use Convenia\Mongodb\Eloquent\HybridRelations;

class User extends Model
{

    use HybridRelations;

    protected $connection = 'mysql';
}

嵌入式关系现在返回 Illuminate\Database\Eloquent\Collection 而不是自定义的 Collection 类。如果您使用了一些特殊方法,请将它们转换为 Collection 操作。

$books = $user->books()->sortBy('title')->get();

安全联系方式

要报告安全漏洞,请按照 这些步骤 操作。