ciayo / moloquent
基于 MongoDB 的 Eloquent 模型和查询构建器,适用于 Laravel (Moloquent)
Requires
- illuminate/container: ^5.5
- illuminate/database: ^5.5
- illuminate/events: ^5.5
- illuminate/support: ^5.5
- mongodb/mongodb: ^1.0.0
Requires (Dev)
- doctrine/dbal: ^2.5
- mockery/mockery: ^0.9
- orchestra/testbench: ^3.1
- phpunit/phpunit: ^6.0
- satooshi/php-coveralls: ^1.0
Suggests
- jenssegers/mongodb-sentry: Add Sentry support to Laravel-MongoDB
- jenssegers/mongodb-session: Add MongoDB session support to Laravel-MongoDB
- dev-master
- 4.2.x-dev
- v3.3.2
- v3.3.1
- v3.3.0
- v3.3.0-alpha
- v3.2.3
- v3.2.2
- v3.2.1
- v3.2.0
- v3.1.4
- v3.1.3
- v3.1.2
- v3.1.1
- v3.1.0
- v3.1.0-alpha
- v3.0.2
- v3.0.1
- v3.0.0
- v3.0.0-beta
- v3.0.0-alpha
- 2.3.x-dev
- v2.3.5
- v2.3.4
- v2.3.3
- v2.3.2
- v2.3.1
- v2.3.0
- 2.2.x-dev
- v2.2.10
- v2.2.9
- v2.2.8
- v2.2.7
- v2.2.6
- v2.2.5
- v2.2.4
- v2.2.3
- v2.2.2
- v2.2.1
- v2.2.0
- 2.1.x-dev
- v2.1.9
- v2.1.8
- v2.1.7
- v2.1.6
- v2.1.5
- v2.1.4
- v2.1.3
- v2.1.2
- v2.1.1
- v2.1.0
- v2.1.0-beta
- 2.0.x-dev
- v2.0.5
- v2.0.4
- v2.0.3
- v2.0.2
- v2.0.1
- v2.0.0
- v2.0.0-alpha
- v1.4.3
- v1.4.2
- v1.4.1
- v1.4.0
- v1.3.2
- v1.3.1
- v1.3.0
- v1.2.9
- v1.2.8
- v1.2.7
- v1.2.6
- v1.2.5
- v1.2.4
- v1.2.3
- v1.2.2
- v1.2.1
- v1.2.0
- v1.1.4
- v1.1.3
- v1.1.2
- v1.1.1
- v1.1.0
- v1.0.8
- v1.0.7
- v1.0.6
- v1.0.5
- v1.0.4
- v1.0.3
- v1.0.2
- v1.0.1
- v1.0.0
- dev-analysis-8AbARP
- dev-analysis-zEPlGG
- dev-develop
This package is not auto-updated.
Last update: 2024-09-29 03:41:51 UTC
README
一个支持 MongoDB 的 Eloquent 模型和查询构建器,使用原始 Laravel API。 这个库扩展了原始 Laravel 类,因此使用的是完全相同的方法。
目录
安装
确保您已安装 MongoDB PHP 驱动。您可以在 https://php.ac.cn/manual/en/mongodb.installation.php 找到安装说明。
警告:旧版 mongo PHP 驱动程序不再支持 >= 3.0 版本。
使用 composer 安装
composer require jenssegers/mongodb
Laravel 版本兼容性
并在 config/app.php 中添加服务提供者
Jenssegers\Mongodb\MongodbServiceProvider::class,
对于与 Lumen 一起使用,在 bootstrap/app.php 中添加服务提供者。在此文件中,您还需要启用 Eloquent。但是,您必须确保您的 $app->withEloquent(); 调用位于 MongodbServiceProvider 注册之后。
$app->register(Jenssegers\Mongodb\MongodbServiceProvider::class); $app->withEloquent();
服务提供者将注册一个 mongodb 数据库扩展与原始数据库管理器。无需注册其他外观或对象。当使用 mongodb 连接时,Laravel 会自动为您提供相应的 mongodb 对象。
对于 Laravel 之外的使用,请查看 Capsule manager 并添加
$capsule->getDatabaseManager()->extend('mongodb', function($config) { return new Jenssegers\Mongodb\Connection($config); });
升级
从版本 2 升级到 3
在这个新的大版本中,我们支持新的 mongodb PHP 扩展,并将模型类的位置移动了,用特质替换了 MySQL 模型类。
请将所有 Jenssegers\Mongodb\Model 引用更改为 Jenssegers\Mongodb\Eloquent\Model,无论是模型文件顶部还是注册的别名。
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class User extends Eloquent {}
如果您使用混合关系,您的 MySQL 类现在应扩展原始 Eloquent 模型类 Illuminate\Database\Eloquent\Model,而不是已删除的 Jenssegers\Eloquent\Model。相反,使用新的 Jenssegers\Mongodb\Eloquent\HybridRelations 特质。这应该使事情更清晰,因为在这个包中只有一个模型类。
use Jenssegers\Mongodb\Eloquent\HybridRelations; class User extends Eloquent { use HybridRelations; protected $connection = 'mysql'; }
嵌入式关系现在返回一个 Illuminate\Database\Eloquent\Collection,而不是自定义的 Collection 类。如果您使用过特殊方法之一,请将它们转换为 Collection 操作。
$books = $user->books()->sortBy('title');
配置
在 config/database.php 中更改默认数据库连接名称
'default' => env('DB_CONNECTION', 'mongodb'),
并添加一个新的 mongodb 连接
'mongodb' => [ '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' => [ 'database' => 'admin' // sets the authentication database required by mongo 3 ] ],
您可以使用以下配置连接到多个服务器或副本集
'mongodb' => [ 'driver' => 'mongodb', 'host' => ['server1', 'server2'], 'port' => env('DB_PORT', 27017), 'database' => env('DB_DATABASE'), 'username' => env('DB_USERNAME'), 'password' => env('DB_PASSWORD'), 'options' => [ 'replicaSet' => 'replicaSetName' ] ],
或者,您可以使用 MongoDB 连接字符串
'mongodb' => [ 'driver' => 'mongodb', 'dsn' => env('DB_DSN'), 'database' => env('DB_DATABASE'), ],
有关其 URI 格式的详细信息,请参阅 MongoDB 官方文档:https://docs.mongodb.com/manual/reference/connection-string/
Eloquent
此包包括一个启用了 MongoDB 的 Eloquent 类,您可以使用它来为相应的集合定义模型。
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class User extends Eloquent {}
请注意,我们没有告诉Eloquent使用哪个集合为User模型。和原始的Eloquent一样,除非显式指定,否则类的小写复数名称将用作集合名称。您可以通过在模型上定义collection属性来指定自定义集合(表别名)。
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class User extends Eloquent { protected $collection = 'users_collection'; }
注意: Eloquent还将假定每个集合都有一个名为id的主键列。您可以通过定义primaryKey属性来覆盖此约定。同样,您也可以定义connection属性来覆盖当使用模型时应使用的数据库连接名称。
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class MyModel extends Eloquent { protected $connection = 'mongodb'; }
其他所有功能(应该)和原始的Eloquent模型一样。有关Eloquent的更多信息,请参阅https://laravel.net.cn/docs/eloquent
可选:别名
您还可以通过在config/app.php中的别名数组中添加以下内容来为MongoDB模型注册别名
'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class,
这将允许您像以下这样使用已注册的别名
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'); });
支持的操作包括
- 创建和删除
- collection
- hasCollection
- index 和 dropIndex(支持复合索引)
- unique
- background, sparse, expire, geospatial(MongoDB特定)
所有其他(不支持)操作都作为虚拟透传方法实现,因为MongoDB不使用预定义的模式。有关模式构建器的更多信息,请参阅https://laravel.net.cn/docs/schema
地理空间索引
地理空间索引对于查询基于位置的文档非常有用。它们有两种形式:2d和2dsphere。使用模式构建器将它们添加到集合中。
添加2d索引
Schema::create('users', function($collection) { $collection->geospatial('name', '2d'); });
添加2dsphere索引
Schema::create('users', function($collection) { $collection->geospatial('name', '2dsphere'); });
扩展
身份验证
如果您想使用Laravel的本地身份验证功能,请注册此包含的服务提供程序
'Jenssegers\Mongodb\Auth\PasswordResetServiceProvider',
此服务提供程序将略微修改内部DatabaseReminderRepository以添加对基于MongoDB的密码提醒的支持。如果您不使用密码提醒,则不需要注册此服务提供程序,其他所有功能都应正常工作。
队列
如果您想将MongoDB用作数据库后端,请在config/queue.php中更改驱动程序
'connections' => [ 'database' => [ 'driver' => 'mongodb', 'table' => 'jobs', 'queue' => 'default', 'expire' => 60, ],
如果您想使用MongoDB来处理失败的工作,请在config/queue.php中更改数据库
'failed' => [ 'database' => 'mongodb', 'table' => 'failed_jobs', ],
并在 config/app.php 中添加服务提供者
Jenssegers\Mongodb\MongodbQueueServiceProvider::class,
Sentry
如果您想与Sentry一起使用此库,请参阅https://github.com/jenssegers/Laravel-MongoDB-Sentry
会话
MongoDB会话驱动程序在单独的包中提供,请参阅https://github.com/jenssegers/Laravel-MongoDB-Session
示例
基本用法
检索所有模型
$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', [16, 18, 20])->get();
当使用whereNotIn时,如果字段不存在,将返回对象。结合使用whereNotNull('age')以排除这些文档。
使用Where Between
$users = User::whereBetween('votes', [1, 100])->get();
Where null
$users = User::whereNull('updated_at')->get();
按顺序排列
$users = User::orderBy('name', 'desc')->get();
偏移量 & 限制
$users = User::skip(10)->take(5)->get();
Distinct
Distinct需要一个字段来返回不同的值。
$users = User::distinct()->get(['name']); // or $users = User::distinct('name')->get();
Distinct可以与where结合使用
$users = User::where('active', true)->distinct('name')->get();
高级Where子句
$users = User::where('name', '=', 'John')->orWhere(function($query) { $query->where('votes', '>', 100) ->where('title', '<>', 'Admin'); }) ->get();
Group By
未分组的选定列将使用$last函数进行聚合。
$users = Users::groupBy('title')->get(['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');
聚合也可以用于子文档
$total = Order::max('suborder.price'); ...
注意:此聚合功能仅适用于单个子文档(如embedsOne),不适用于子文档数组(如embedsMany)
类似
$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, ['group' => 'thirty something']); User::where('bmi', 30)->decrement('bmi', 1, ['category' => 'overweight']);
软删除
当软删除模型时,实际上并未从数据库中删除。相反,会在记录上设置deleted_at时间戳。要启用模型的软删除,请将SoftDeletingTrait应用于模型
use Jenssegers\Mongodb\Eloquent\SoftDeletes; class User extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; }
更多信息请查看 https://laravel.net.cn/docs/eloquent#soft-deleting
MongoDB特定运算符
存在
匹配具有指定字段的文档。
User::where('age', 'exists', true)->get();
所有
匹配包含查询中指定所有元素的数组。
User::where('roles', 'all', ['moderator', 'author'])->get();
大小
如果数组字段是指定的尺寸,则选择文档。
User::where('tags', 'size', 3)->get();
正则表达式
选择匹配指定正则表达式的值的文档。
User::where('name', 'regex', new \MongoDB\BSON\Regex("/.*doe/i"))->get();
注意:您还可以使用Laravel正则表达式操作。这些操作更灵活,并将自动将您的正则表达式字符串转换为MongoDB\BSON\Regex对象。
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', [10, 0])->get();
附近
注意:指定坐标的顺序为:经度, 纬度。
$users = User::where('location', 'near', [ '$geometry' => [ 'type' => 'Point', 'coordinates' => [ -0.1367563, 51.5100913, ], ], '$maxDistance' => 50, ]);
GeoWithin
$users = User::where('location', 'geoWithin', [ '$geometry' => [ 'type' => 'Polygon', 'coordinates' => [[ [ -0.1450383, 51.5069158, ], [ -0.1367563, 51.5100913, ], [ -0.1270247, 51.5013233, ], [ -0.1450383, 51.5069158, ], ]], ], ]);
GeoIntersects
$locations = Location::where('location', 'geoIntersects', [ '$geometry' => [ 'type' => 'LineString', 'coordinates' => [ [ -0.144044, 51.515215, ], [ -0.129545, 51.507864, ], ], ], ]);
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(['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\Eloquent\Model as Eloquent; class User extends Eloquent { protected $dates = ['birthday']; }
允许您执行以下查询
$users = User::where('birthday', '>', new DateTime('-18 years'))->get();
关系
支持的关联包括
- hasOne
- hasMany
- belongsTo
- belongsToMany
- embedsOne
- embedsMany
示例
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class User extends Eloquent { public function items() { return $this->hasMany('Item'); } }
及其反向关系
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class Item extends Eloquent { public function user() { return $this->belongsTo('User'); } }
belongsToMany关系将不会使用“交叉”表,而是将id推送到related_ids属性中。这使得belongsToMany方法的第二个参数变得无用。如果您想为您的关联定义自定义键,请将其设置为null
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class User extends Eloquent { public function groups() { return $this->belongsToMany('Group', null, 'user_ids', 'group_ids'); } }
其他关系尚未支持,但将来可能添加。更多关于这些关系的详情请参阅https://laravel.net.cn/docs/eloquent#relationships
EmbedsMany关系
如果您想嵌入模型而不是引用它们,可以使用embedsMany关系。这种关系与hasMany关系类似,但它将模型嵌入到父对象中。
记住:这些关系返回Eloquent集合,而不是查询构建器对象!
use Jenssegers\Mongodb\Eloquent\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(['title' => 'A Game of Thrones']); $user = User::first(); $book = $user->books()->save($book); // 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 = $user->books()->first(); $book->delete(); // or $user->books()->destroy($book);
如果您想添加或删除嵌入模型,而不接触数据库,可以使用associate和dissociate方法。要最终将更改写入数据库,请保存父对象
$user->books()->associate($book); $user->save();
与其他关系一样,embedsMany假设关系基于模型名称的本地键。您可以通过向embedsMany方法传递第二个参数来覆盖默认的本地键
return $this->embedsMany('Book', 'local_key');
嵌入关系将返回嵌入项的集合,而不是查询构建器。请在此处查看可用的操作:https://laravel.net.cn/docs/master/collections
EmbedsOne关系
embedsOne关系与EmbedsMany关系类似,但只嵌入单个模型。
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class Book extends Eloquent { public function author() { return $this->embedsOne('Author'); } }
您可以通过动态属性访问嵌入的模型
$author = Book::first()->author;
嵌入模型的插入和更新与hasOne关系类似
$author = new Author(['name' => 'John Doe']); $book = Books::first(); $author = $book->author()->save($author); // or $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);
MySQL关系
如果您使用的是混合MongoDB和SQL设置,那么您很幸运!模型将根据相关模型的类型自动返回MongoDB或SQL关系。当然,如果要让此功能双向工作,您的SQL模型需要使用Jenssegers\Mongodb\Eloquent\HybridRelations特性。请注意,此功能仅适用于hasOne、hasMany和belongsTo关系。
基于SQL的用户模型示例
use Jenssegers\Mongodb\Eloquent\HybridRelations; class User extends Eloquent { use HybridRelations; protected $connection = 'mysql'; public function messages() { return $this->hasMany('Message'); } }
以及基于MongoDB的消息模型
use Jenssegers\Mongodb\Eloquent\Model as Eloquent; class Message extends Eloquent { protected $connection = 'mongodb'; public function user() { return $this->belongsTo('User'); } }
原始表达式
这些表达式将被直接注入到查询中。
User::whereRaw(['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(); });
可选:如果不传递闭包到raw方法,则内部MongoCollection对象是可访问的
$model = User::raw()->findOne(['age' => array('$lt' => 18)]);
可以像这样访问内部MongoClient和MongoDB对象
$client = DB::getMongoClient(); $db = DB::getMongoDB();
MongoDB特定操作
游标超时
为防止MongoCursorTimeout异常,您可以手动设置一个将应用于游标的超时值
DB::collection('users')->timeout(-1)->get();
Upsert
更新或插入文档。将update方法的附加选项直接传递给原生update方法。
DB::collection('users')->where('name', 'John') ->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'); DB::collection('users')->where('name', 'John')->push('messages', ['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', ['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();