ldavidsp/laravel-couchdb

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

v2.6.0 2021-08-28 18:08 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别名以及一些额外的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');

Wheres

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

高级Wheres

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

正则表达式

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

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

删除模型

要删除模型,只需在实例上调用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"表,而是将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

嵌套Many关系

如果您想嵌入模型而不是引用它们,可以使用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的贡献者,因为此项目的许多代码和结构都来自那里。