guflores-web/laravel-couchdb

基于Robson Nascimento项目的CouchDB v2.0.0版本的Eloquent模型和查询构建器,适用于Laravel

2.5.2 2021-06-04 19:34 UTC

README

Build Status StyleCI codecov.io

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

使用前须知

  • CouchDB处理Mango查询有许多限制,这迫使我们必须在内存中处理某些操作,这直接影响了我们库的性能,请查看CouchDB限制限制部分以获取更多详细信息。

目录

安装

使用Composer安装

composer require robsonvn/laravel-couchdb

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

Robsonvn\CouchDB\ServiceProvider::class,

Laravel版本兼容性

目前,此项目仅与Laravel 5.4.x兼容

配置

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

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

并添加一个新的couchdb连接

'couchdb' => [    
    'driver'   => 'couchdb',
    'type'     => env('DB_CONNECTION_TYPE', 'socket'),
    'host'     => env('DB_HOST', 'localhost'),
    'ip'       => env('DB_IP', null),
    'port'     => env('DB_PORT', '5984'),
    'dbname'   => env('DB_DATABASE', 'forge'),
    'user'     => env('DB_USERNAME', null),
    'password' => env('DB_PASSWORD', null),
    'logging'  => env('DB_LOGGING', false),
],

并在您的.env文件中添加此内容

DB_CONNECTION=couchdb
DB_HOST=dbhost
DB_PORT=5984
DB_DATABASE=dbname
DB_USERNAME=
DB_PASSWORD=

请注意,数据库用户必须是管理员,因为此库会动态创建索引(design_docs)

您可以在此处了解更多关于CouchDB授权的信息。

Eloquent

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

use Robsonvn\CouchDB\Eloquent\Model as Eloquent;

class Book extends Eloquent{}

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

use Robsonvn\CouchDB\Eloquent\Model as Eloquent;

class Book extends Eloquent{
  protected $collection = 'books_collection';
}

查询构建器

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

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

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

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

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

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

扩展

身份验证

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

Robsonvn\CouchDB\Auth\PasswordResetServiceProvider::class,

此服务提供者将略微修改内部DatabaseTokenRepository以添加对基于CouchDB的密码提醒的支持。如果您不使用密码提醒,则不需要注册此服务提供者,其他所有内容应正常工作。

您还需要在您的User类中扩展CouchDB Authenticatable类,而不是使用本地的一个。

use Robsonvn\CouchDB\Auth\User as Authenticatable;

class User extends Authenticatable
{
}

队列

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

'connections' => [
    'database' => [
        'driver' => 'couchdb',
        'table'  => 'jobs',
        'queue'  => 'default',
        'expire' => 60,
    ],

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

'failed' => [
    'database' => 'couchdb',
    'table'    => 'failed_jobs',
    ],

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

Robsonvn\CouchDB\CouchDBQueueServiceProvider::class,

示例

基本用法

检索所有模型

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

Order By

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

Offset & Limit

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

高级Where

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

Like(大小写敏感)

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

Like(大小写不敏感)

$user = Comment::where('body', 'ilike', '%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 Robsonvn\CouchDB\Eloquent\SoftDeletes;

class User extends Eloquent {

    use SoftDeletes;

    protected $dates = ['deleted_at'];

}

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

CouchDB特定运算符

Exists

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

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

All

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

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

Size

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

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

Regex

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

User::where('name', 'regex', '(?i).*doe$')->get();
User::where('name', 'not regex', '(?i).*doe$')->get()

注意: Mango查询使用Erlang正则表达式实现。

大多数选择器表达式与您预期的给定运算符完全一样。$regex运算符使用的匹配算法目前基于Perl兼容正则表达式(PCRE)库。但是,并非实现了PCRE库的全部功能,$regex运算符的一些部分超出了PCRE提供的功能。有关实现信息的更多信息,请参阅Erlang正则表达式信息https://erlang.org.cn/doc/man/re.html

Type

如果字段是指定的类型,则选择文档。有效值是 "null","boolean","number","string","array",和 "object"。

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

Mod

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

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

插入、更新和删除

插入、更新和删除记录的工作方式与原始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();

删除模型

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

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

或通过其键删除模型

User::destroy('517c43667db388101e00000f');

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

日期

Eloquent允许您使用Carbon/DateTime对象。内部,这些日期将在保存到数据库时转换为格式化的字符串 'yyyy-mm-dd H:i:s'。如果您希望在非默认日期字段上使用此功能,则需要手动指定它们,如这里所述:https://laravel.net.cn/docs/eloquent#date-mutators

示例

use Robsonvn\CouchDB\Eloquent\Model as Eloquent;

class User extends Eloquent {

    protected $dates = ['birthday'];

}

允许您执行类似以下查询

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

关系

支持的关系有

  • hasOne
  • hasMany
  • belongsTo
  • belongsToMany
  • morphToMany
  • embedsOne
  • embedsMany

示例

use Robsonvn\CouchDB\Eloquent\Model as Eloquent;

class User extends Eloquent {

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

}

以及反向关系

use Robsonvn\CouchDB\Eloquent\Model as Eloquent;

class Item extends Eloquent {

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

}

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

use Robsonvn\CouchDB\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 Robsonvn\CouchDB\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 方法更新嵌入的模型

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

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

$book->save();

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

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

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

EmbedsOne 关系

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

use Robsonvn\CouchDB\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 方法更新嵌入的模型

$author = $book->author;

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

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

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

原始表达式

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

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

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

// Returns a collection of User models.
$models = User::raw(function($collection)
{
    return $collection->find(['_id'=>['$gt'=>null]]);
});

// Returns the original CouchDB response.
$cursor = DB::collection('users')->raw(function($collection)
{
    return $collection->find(['_id'=>['$gt'=>null]]);
});

可以通过这种方式访问内部 CouchDBClient

$client = DB::getCouchDBClient();

CouchDB限制

  • 目前,无法使用 Mango 查询更新和删除。在这种情况下,我们必须查询数据,将其带入内存,更新字段并批量更新。
  • CouchDB 在索引方面非常敏感,甚至文档 也建议 总是明确指定查询应使用的索引。在这种情况下,我们自动在飞地创建所有必需的索引。
  • CouchDB 没有像 MongoDB 那样的集合概念,因此我们通过在每个单独的文档中添加一个属性(类型)来使用“集合”。请将类型视为保留属性。使用集合是必需的。

限制

  • 由于我们创建索引的方式,这个库目前无法与启用全文搜索的引擎一起使用。
  • 聚合、按组操作和 distinct 操作尚不支持。
  • 如果您想使用任何扩展原始 Eloquent 类的库,您可能必须将其分叉并更改到我们的类。

待办事项

  • 添加与全文搜索引擎兼容的功能。
  • 添加对聚合、按组操作和 distinct 操作的支持。
  • 创建查询游标。
  • 添加使用点符号法获取已转换属性的支持。

特别感谢

Fred Booking 对此项目的支持。

Jens SegersLaravel MongoDB 贡献者,因为此项目的许多代码和结构都来自那里。