robsonvn/laravel-couchdb

此包已被放弃,不再维护。未建议替代包。

基于 CouchDB v2.0.0 的 Laravel Eloquent 模型和查询构建器

2.5.0 2020-04-26 00:00 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的本地Auth功能,请注册这个包含的服务提供者

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

OrderBy

$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特定运算符

存在

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

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

所有

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

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

大小

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

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

类型

如果字段是指定的类型,则选择文档。有效值是"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();

删除模型

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

$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 关系将不会使用 "关联" 表,而是将 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 贡献者,因为此项目的许多代码和结构都来自那里。