elsayed85 / couchbase
基于 Couchbase 的 Laravel Eloquent 模型和查询构建器
Requires
- php: ^7.3|^8.0
- ext-couchbase: >=3.0
- illuminate/container: ^7.0|^8.0|^9.0|^10.0
- illuminate/database: ^7.0|^8.0|^9.0|^10.0
- illuminate/events: ^7.0|^8.0|^9.0|^10.0
- illuminate/support: ^7.0|^8.0|^9.0|^10.0
Requires (Dev)
- ext-json: *
- mockery/mockery: ^1.4.2
- orchestra/testbench: ^6.2|^7.0
- phpunit/phpunit: ^9.3.3
- vlucas/phpdotenv: ^5.3
This package is auto-updated.
Last update: 2024-09-16 17:44:45 UTC
README
一个支持 Couchbase 的 Eloquent 模型和查询构建器,使用原始 Laravel API。 此库扩展了原始 Laravel 类,因此使用完全相同的方法。
鸣谢
目录
安装
Couchbase 兼容性
请确保您已安装 Couchbase PHP 驱动。您可以在以下位置找到安装说明:http://developer.couchbase.com/documentation/server/current/sdk/php/start-using-sdk.html
使用 composer 安装
composer require friendsofcat/laravel-couchbase
并在 config/app.php
中添加服务提供者
FriendsOfCat\Couchbase\CouchbaseServiceProvider::class,
对于与 Lumen 的使用,在 bootstrap/app.php
中添加服务提供者。在此文件中,您还需要启用 Eloquent。但是,您必须确保对 $app->withEloquent();
的调用位于注册 CouchbaseServiceProvider
下方。
$app->register(FriendsOfCat\Couchbase\CouchbaseServiceProvider::class); $app->withEloquent();
服务提供者将在原始数据库管理器中注册 Couchbase 数据库扩展。不需要注册额外的外观或对象。当使用 couchbase 连接时,Laravel 将自动为您提供相应的 couchbase 对象。
对于 Laravel 之外的使用,请参阅 Capsule manager 并添加
$capsule->getDatabaseManager()->extend('couchbase', function($config) { return new FriendsOfCat\Couchbase\Connection($config); });
使用方法
composer require friendsofcat/laravel-couchbase
- 并添加一个新的 couchbase 连接
'couchbase' => [ 'driver' => 'couchbase', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', 8091), 'bucket' => env('DB_DATABASE'), 'username' => env('DB_USERNAME'), ],
- 您可以使用以下配置连接到多个服务器或复制集
'couchbase' => [ 'driver' => 'couchbase', 'host' => ['host1', 'host2'], 'port' => env('DB_PORT', 8091), 'bucket' => env('DB_DATABASE'), 'username' => env('DB_USERNAME'), ],
- 模型使用
<?php use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent; class User extends Eloquent { $connection = 'couchbase'; }
更多内容请参阅下面的 Eloquent 部分
命令
couchbase couchbase:bucket:create 创建一个桶 couchbase:bucket:create-primary-index 在桶上创建索引以允许执行 nql 查询 couchbase:bucket:delete 删除一个桶 couchbase:bucket:flush 从桶中删除所有数据(清空数据库) couchbase:bucket:list 列出集群中可用的桶 couchbase:cluster:init 在使用之前初始化 couchbase 集群
在 Laravel 中使用之前
请注意,以下所有命令都可以在 localhost:8091
的浏览器中完成
- 在使用之前初始化集群
php artisan couchbase:cluster:init
- 创建一个桶
php artisan couchbase:bucket:create --bucket canvas
Eloquent
此包包括一个启用了 Couchbase 的 Eloquent 类,您可以使用它来定义对应集合的模型。
use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent; class User extends Eloquent {}
由于 Couchbase 不提供表的概念,文档将通过一个名为 _type
的属性来定义。像原始 Eloquent 一样,类的小写复数名称将被用作“表”名称,并将放置在每个文档的 _type
属性中。
您可以通过在模型上定义 table
属性来指定自定义类型(表的别名)
use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent; class User extends Eloquent { protected $table = 'my_users'; }
注意: Eloquent 还假定每个集合都有一个名为 _id
的主键列。您可以通过定义 primaryKey
属性来覆盖此约定。同样,您还可以定义 connection
属性来覆盖在利用模型时应该使用的数据库连接名称。
use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent; class MyModel extends Eloquent { protected $connection = 'couchbase'; }
其余的(应该)与原始 Eloquent 模型一样工作。有关 Eloquent 的更多信息,请参阅 https://laravel.net.cn/docs/eloquent
可选:别名
您还可以通过在 config/app.php
中的别名数组中添加以下内容来注册 Couchbase 模型的别名
'CouchbaseModel' => 'FriendsOfCat\Couchbase\Eloquent\Model',
这将允许您像下面这样使用已注册的别名
class MyModel extends CouchbaseModel {}
查询构建器
数据库驱动程序可以直接连接到原始查询构建器。在使用Couchbase连接时,您将能够构建流畅的查询以执行数据库操作。
$users = DB::table('users')->get(); $user = DB::table('users')->where('name', 'John')->first();
如果您没有更改默认数据库连接,则在查询时需要指定它。
$user = DB::connection('couchbase')->table('users')->get();
有关查询构建器的更多信息,请参阅https://laravel.net.cn/docs/queries
模式
由于此Couchbase驱动程序实现使用单个桶存储所有文档,因此未实现Schema构建器。
示例
基本用法
检索所有模型
$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();
使用Where Between
$users = User::whereBetween('votes', [1, 100])->get();
Where null
$users = User::whereNull('updated_at')->get();
Where缺失
$users = User::whereIsMissing('updated_at')->get();
Where有值
$users = User::whereIsValued('updated_at')->get();
Order By
$users = User::orderBy('name', 'desc')->get();
Offset & Limit
$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']);
聚合
$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');
Like
$user = Comment::where('body', 'like', '%spam%')->get();
注意:Couchbase中的Like检查是区分大小写的
增加或减少列的值
对指定的属性执行增加或减少(默认为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 FriendsOfCat\Couchbase\Eloquent\SoftDeletes; class User extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; }
有关更多信息,请参阅https://laravel.net.cn/docs/eloquent#soft-deleting
插入、更新和删除
插入、更新和删除记录的工作方式与原始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
关系
支持的关系包括
- hasOne
- hasMany
- belongsTo
- belongsToMany
- embedsOne
- embedsMany
示例
use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent; class User extends Eloquent { public function items() { return $this->hasMany('Item'); } }
和反向关系
use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent; class Item extends Eloquent { public function user() { return $this->belongsTo('User'); } }
belongsToMany关系将不会使用中继"表",而是将id推送到related_ids属性。这使得belongsToMany方法的第二个参数变得无用。如果您想为您的关联定义自定义键,将其设置为null
use FriendsOfCat\Couchbase\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 FriendsOfCat\Couchbase\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);
如果您想添加或删除嵌入式模型,而不接触数据库,可以使用 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 FriendsOfCat\Couchbase\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);
MySQL 关系
如果您正在使用混合 Couchbase 和 SQL 设置,那真是太好了!模型将根据相关模型类型自动返回 Couchbase 或 SQL 关系。当然,如果您想这种功能双向工作,您的 SQL 模型需要使用 FriendsOfCat\Couchbase\Eloquent\HybridRelations
特性。请注意,此功能仅适用于 hasOne、hasMany 和 belongsTo 关系。
基于 SQL 的用户模型示例
use FriendsOfCat\Couchbase\Eloquent\HybridRelations; class User extends Eloquent { use HybridRelations; protected $connection = 'mysql'; public function messages() { return $this->hasMany('Message'); } }
以及基于 Couchbase 的消息模型
use FriendsOfCat\Couchbase\Eloquent\Model as Eloquent; class Message extends Eloquent { protected $connection = 'couchbase'; public function user() { return $this->belongsTo('User'); } }
查询缓存
您可以使用 remember 方法轻松缓存查询结果
$users = User::remember(10)->get();
来源:https://laravel.net.cn/docs/queries#caching-queries
查询日志
默认情况下,Laravel 会记录当前请求中运行的所有查询。然而,在某些情况下,例如在插入大量行时,这可能导致应用程序使用过多的内存。要禁用日志,您可以使用 disableQueryLog
方法
DB::connection()->disableQueryLog();
来源:https://laravel.net.cn/docs/database#query-logging
测试
- 创建存储桶
- 创建存储桶主索引
- 运行测试
- 使用
RefreshDatabase
特性在测试之间清除数据库
待办事项
这并不是一个功能齐全的 Eloquent 驱动器。还有一些地方需要关注。仅举几个例子
- 使用 collection/scope 实现 table 概念,而不是
type
。这可能提高性能 - 测试命令
- 测试分页
- 辅助
uniqueId
- 自定义
RefreshDatabase
特性以重新创建存储桶 - 添加
LazilyRefreshDatabase
以替代 RefreshDatabase Lead
// RefreshDatabase $this->artisan(BucketDelete::class); $this->artisan(BucketCreate::class); $this->artisan(BucketCreatePrimaryIndex::class); // check hook afterApplicationCreated, beforeApplicationDestroyed