• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

jenssegers/laravel-mongodb: A MongoDB based Eloquent model and Query builder for ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

jenssegers/laravel-mongodb

开源软件地址(OpenSource Url):

https://github.com/jenssegers/laravel-mongodb

开源编程语言(OpenSource Language):

PHP 99.9%

开源软件介绍(OpenSource Introduction):

Laravel MongoDB

Latest Stable Version Total Downloads Build Status codecov Donate

This package adds functionalities to the Eloquent model and Query builder for MongoDB, using the original Laravel API. This library extends the original Laravel classes, so it uses exactly the same methods.

Installation

Make sure you have the MongoDB PHP driver installed. You can find installation instructions at http://php.net/manual/en/mongodb.installation.php

Laravel version Compatibility

Laravel Package Maintained
9.x 3.9.x
8.x 3.8.x
7.x 3.7.x
6.x 3.6.x
5.8.x 3.5.x
5.7.x 3.4.x
5.6.x 3.4.x
5.5.x 3.3.x
5.4.x 3.2.x
5.3.x 3.1.x or 3.2.x
5.2.x 2.3.x or 3.0.x
5.1.x 2.2.x or 3.0.x
5.0.x 2.1.x
4.2.x 2.0.x

Install the package via Composer:

$ composer require jenssegers/mongodb

Laravel

In case your Laravel version does NOT autoload the packages, add the service provider to config/app.php:

Jenssegers\Mongodb\MongodbServiceProvider::class,

Lumen

For usage with Lumen, add the service provider in bootstrap/app.php. In this file, you will also need to enable Eloquent. You must however ensure that your call to $app->withEloquent(); is below where you have registered the MongodbServiceProvider:

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

$app->withEloquent();

The service provider will register a MongoDB database extension with the original database manager. There is no need to register additional facades or objects.

When using MongoDB connections, Laravel will automatically provide you with the corresponding MongoDB objects.

Non-Laravel projects

For usage outside Laravel, check out the Capsule manager and add:

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

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

Testing

To run the test for this package, run:

docker-compose up

Database Testing

To reset the database after each test, add:

use Illuminate\Foundation\Testing\DatabaseMigrations;

Also inside each test classes, add:

use DatabaseMigrations;

Keep in mind that these traits are not yet supported:

  • use Database Transactions;
  • use RefreshDatabase;

Configuration

You can use MongoDB either as the main database, either as a side database. To do so, add a new mongodb connection to config/database.php:

'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' => [
        // here you can pass more settings to the Mongo Driver Manager
        // see https://www.php.net/manual/en/mongodb-driver-manager.construct.php under "Uri Options" for a list of complete parameters that you can use

        'database' => env('DB_AUTHENTICATION_DATABASE', 'admin'), // required with Mongo 3+
    ],
],

For multiple servers or replica set configurations, set the host to an array and specify each server host:

'mongodb' => [
    'driver' => 'mongodb',
    'host' => ['server1', 'server2', ...],
    ...
    'options' => [
        'replicaSet' => 'rs0',
    ],
],

If you wish to use a connection string instead of full key-value params, you can set it so. Check the documentation on MongoDB's URI format: https://docs.mongodb.com/manual/reference/connection-string/

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

Eloquent

Extending the base model

This package includes a MongoDB enabled Eloquent class that you can use to define models for corresponding collections.

use Jenssegers\Mongodb\Eloquent\Model;

class Book extends Model
{
    //
}

Just like a normal model, the MongoDB model class will know which collection to use based on the model name. For Book, the collection books will be used.

To change the collection, pass the $collection property:

use Jenssegers\Mongodb\Eloquent\Model;

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

NOTE: MongoDB documents are automatically stored with a unique ID that is stored in the _id property. If you wish to use your own ID, substitute the $primaryKey property and set it to your own primary key attribute name.

use Jenssegers\Mongodb\Eloquent\Model;

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

// Mongo 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']);

Likewise, you may define a connection property to override the name of the database connection that should be used when utilizing the model.

use Jenssegers\Mongodb\Eloquent\Model;

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

Extending the Authenticable base model

This package includes a MongoDB Authenticatable Eloquent class Jenssegers\Mongodb\Auth\User that you can use to replace the default Authenticatable class Illuminate\Foundation\Auth\User for your User model.

use Jenssegers\Mongodb\Auth\User as Authenticatable;

class User extends Authenticatable
{

}

Soft Deletes

When soft deleting a model, it is not actually removed from your database. Instead, a deleted_at timestamp is set on the record.

To enable soft deletes for a model, apply the Jenssegers\Mongodb\Eloquent\SoftDeletes Trait to the model:

use Jenssegers\Mongodb\Eloquent\SoftDeletes;

class User extends Model
{
    use SoftDeletes;

    protected $dates = ['deleted_at'];
}

For more information check Laravel Docs about Soft Deleting.

Guarding attributes

When choosing between guarding attributes or marking some as fillable, Taylor Otwell prefers the fillable route. This is in light of recent security issues described here.

Keep in mind guarding still works, but you may experience unexpected behavior.

Dates

Eloquent allows you to work with Carbon or DateTime objects instead of MongoDate objects. Internally, these dates will be converted to MongoDate objects when saved to the database.

use Jenssegers\Mongodb\Eloquent\Model;

class User extends Model
{
    protected $dates = ['birthday'];
}

This allows you to execute queries like this:

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

Basic Usage

Retrieving all models

$users = User::all();

Retrieving a record by primary key

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

Where

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

OR Statements

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

AND statements

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

whereIn

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

When using whereNotIn objects will be returned if the field is non-existent. Combine with whereNotNull('age') to leave out those documents.

whereBetween

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

whereNull

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

whereDate

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

The usage is the same as whereMonth / whereDay / whereYear / whereTime

Advanced wheres

$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 (skip & take)

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

groupBy

Selected columns that are not grouped will be aggregated with the $last function.

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

Distinct

Distinct requires a field for which to return the distinct values.

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

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

Distinct can be combined with where:

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

Like

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

Aggregation

Aggregations are only available for MongoDB versions greater than 2.2.x

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

Aggregations can be combined with where:

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

Aggregations can be also used on sub-documents:

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

NOTE: This aggregation only works with single sub-documents (like EmbedsOne) not subdocument arrays (like EmbedsMany).

Incrementing/Decrementing the value of a column

Perform increments or decrements (default 1) on specified attributes:

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

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

The number of updated objects is returned:

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

You may also specify additional columns to update:

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

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

MongoDB-specific operators

Exists

Matches documents that have the specified field.

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

All

Matches arrays that contain all elements specified in the query.

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

Size

Selects documents if the array field is a specified size.

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

Regex

Selects documents where values match a specified regular expression.

use MongoDB\BSON\Regex;

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

NOTE: you can also use the Laravel regexp operations. These are a bit more flexible and will automatically convert your regular expression string to a MongoDB\BSON\Regex object.

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

The inverse of regexp:

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

Type

Selects documents if a field is of the specified type. For more information check: http://docs.mongodb.org/manual/reference/operator/query/type/#op._S_type

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

Mod

Performs a modulo operation on the value of a field and selects documents with a specified result.

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

MongoDB-specific Geo operations

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

Inserts, updates and deletes

Inserting, updating and deleting records works just like the original Eloquent. Please check Laravel Docs' Eloquent section.

Here, only the MongoDB-specific operations are specified.

MongoDB specific operations

Raw Expressions

These expressions will be injected directly into the query.

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

You can also perform raw expressions on the internal MongoCollection object. If this is executed on the model class, it will return a collection of models.

If this is executed on the query builder, it will return the original response.

Cursor timeout

To prevent MongoCursorTimeout exceptions, you can manually set a timeout value that will be applied to the cursor:

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

Upsert

Update or insert a document. Additional options for the update method are passed directly to the native update method.

// Query Builder
DB::collection('users'
                      

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
bestmomo/laravel5-example: Simple laravel5 example for tutorial发布时间:2022-07-07
下一篇:
laravel/lumen: The Laravel Lumen Framework.发布时间:2022-07-07
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap