roi-up-agency / laravel-cassandra
Cassandra Eloquent 模型和查询构建器,适用于 Laravel
Requires
- php: >=7.1.0
- datastax/php-driver: ^1.2
- illuminate/container: ~5.8
- illuminate/database: ~5.8
- illuminate/events: ~5.8
- illuminate/support: ~5.8
README
内容
将 Cassandra 集成到您的 Laravel 应用中,使用 Laravel 自身的 API 和方法。
目录
安装
请确保已安装 Cassandra PHP 驱动。 https://github.com/datastax/php-driver
使用 composer 安装
composer require sashalenz/laravel-cassandra
Laravel 版本兼容性
在 config/app.php 中添加 Cassandra 服务提供者
RoiupAgency\Cassadra\CassandraServiceProvider::class,
对于与 Lumen 一起使用,请在 bootstrap/app.php 中添加服务提供者。在此文件中,您还需要启用 Eloquent。但是,您必须确保对 $app->withEloquent(); 的调用在注册 CassandraServiceProvider 之后进行。
$app->register('RoiupAgency\Cassadra\CassandraServiceProvider'); $app->withEloquent();
服务提供者将向原始数据库管理器注册一个 Cassandra 数据库扩展。无需注册额外的外观或对象。当使用 cassandra 连接时,Laravel 将自动为您提供相应的 cassandra 对象。
配置
在 app/config/database.php 中更改默认数据库连接名称
'default' => env('DB_CONNECTION', 'cassandra'),
并添加一个新的 cassandra 连接
'cassandra' => [ 'driver' => 'cassandra', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', 27017), 'database' => env('DB_DATABASE', ''), 'username' => env('DB_USERNAME', ''), 'password' => env('DB_PASSWORD', ''), 'options' => [ 'db' => 'admin' // sets the authentication database required by cassandra 3 ] ],
您可以使用以下配置连接到多个服务器或副本集
'cassandra' => [ 'driver' => 'cassandra', 'host' => ['server1', 'server2'], 'port' => env('DB_PORT', 27017), 'database' => env('DB_DATABASE', ''), 'username' => env('DB_USERNAME', ''), 'password' => env('DB_PASSWORD', ''), 'options' => ['replicaSet' => 'replicaSetName'] ],
Eloquent
此软件包包含一个启用了 Cassandra 的 Eloquent 类,您可以使用它来为相应的集合定义模型。
use RoiupAgency\Cassadra\Eloquent\Model as Eloquent; class User extends Eloquent {}
注意,我们没有告诉 Eloquent 为 User 模型使用哪个集合。就像原始 Eloquent 一样,除非显式指定,否则类的低格式复数名称将被用作表名。您可以通过在模型上定义 collection 属性来指定自定义集合(表别名)。
use RoiupAgency\Cassadra\Eloquent\Model as Eloquent; class User extends Eloquent { protected $collection = 'users_collection'; }
注意: Eloquent 还假设每个集合都有一个名为 id 的主键列。您可以通过定义 primaryKey 属性来覆盖此约定。同样,您也可以定义一个 connection 属性来覆盖在利用模型时应该使用的数据库连接名称。
use RoiupAgency\Cassadra\Eloquent\Model as Eloquent; class MyModel extends Eloquent { protected $connection = 'cassandra'; }
其他一切(应该)都像原始 Eloquent 模型一样工作。有关 Eloquent 的更多信息,请参阅 https://laravel.net.cn/docs/eloquent
可选:别名
您还可以通过在 app/config/app.php 中的别名数组中添加以下内容来注册 Cassandra 模型的别名
'Moloquent' => 'RoiupAgency\Cassadra\Eloquent\Model',
这将允许您使用已注册的别名,如下所示
class MyModel extends Moloquent {}
查询构建器
数据库驱动程序直接连接到原始查询构建器。当使用 cassandra 连接时,您将能够构建流畅的查询以执行数据库操作。为了您的方便,还有一个 collection 别名用于 table 以及一些额外的 cassandra 特定运算符/操作。
$users = DB::collection('users')->get(); $user = DB::collection('users')->where('name', 'John')->first();
如果您没有更改默认数据库连接,则需要在查询时指定它。
$user = DB::connection('cassandra')->collection('users')->get();
有关查询构建器的更多信息,请参阅 https://laravel.net.cn/docs/queries
模式
数据库驱动程序还支持(有限的)模式构建器。您可以轻松地操作集合并设置索引
Schema::create('users', function($collection) { $collection->index('name'); $collection->unique('email'); });
支持的运算包括
- 创建和删除
- 集合
- hasCollection
- 索引和删除索引(支持复合索引)
- 唯一
- 背景、稀疏、过期(Cassandra 特定)
所有其他(不支持)的操作都作为虚拟透传方法实现,因为Cassandra不使用预定义模式。有关模式构建器的更多信息,请参阅https://laravel.net.cn/docs/schema
扩展
身份验证
如果您想使用Laravel的本地身份验证功能,请注册此包含的服务提供程序
'RoiupAgency\Cassadra\Auth\PasswordResetServiceProvider',
此服务提供程序将稍微修改内部DatabaseReminderRepository,以添加基于Cassandra的密码提醒支持。如果您不使用密码提醒,则无需注册此服务提供程序,其他所有内容都应该正常工作。
队列
如果您想使用Cassandra作为数据库后端,请更改config/queue.php中的驱动程序
'connections' => [ 'database' => [ 'driver' => 'cassandra', 'table' => 'jobs', 'queue' => 'default', 'expire' => 60, ],
示例
基本用法
检索所有模型
$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();
Distinct
Distinct需要一个字段来返回不同的值。
$users = User::distinct()->get(['name']); // or $users = User::distinct('name')->get();
Distinct可以与where结合使用
$users = User::where('active', true)->distinct('name')->get();
高级Wheres
$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']);
聚合
聚合仅在Cassandra版本大于2.2时可用。
$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();
增加或减少列的值
对指定的属性执行增量或减量(默认为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 RoiupAgency\Cassadra\Eloquent\SoftDeletes; class User extends Eloquent { use SoftDeletes; protected $dates = ['deleted_at']; }
有关更多信息,请参阅https://laravel.net.cn/docs/eloquent#soft-deleting
Cassandra特定运算符
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', new CassandraRegex("/.*doe/i"))->get();
注意:您还可以使用Laravel正则表达式操作。这些操作更灵活,并且会自动将您的正则表达式字符串转换为CassandraRegex对象。
User::where('name', 'regexp', '/.*doe/i'))->get();
及其逆操作
User::where('name', 'not regexp', '/.*doe/i'))->get();
Type
如果字段是指定的类型,则选择文档。有关更多信息,请参阅:http://docs.cassandra.org/manual/reference/operator/query/type/#op._S_type
User::where('age', 'type', 2)->get();
Mod
对字段的值执行取模运算,并选择具有指定结果的文档。
User::where('age', 'mod', [10, 0])->get();
Where
匹配满足JavaScript表达式的文档。有关更多信息,请参阅:http://docs.cassandra.org/manual/reference/operator/query/where/#op._S_where
插入、更新和删除
插入、更新和删除记录的工作方式与原始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();
还支持upsert操作,请参阅https://github.com/sashalenz/laravel-cassandra#cassandra-specific-operations
删除模型
要删除模型,只需在实例上调用delete方法
$user = User::first(); $user->delete();
或通过其键删除模型
User::destroy('517c43667db388101e00000f');
关于模型操作更多信息,请查阅 https://laravel.net.cn/docs/eloquent#insert-update-delete
日期
Eloquent 允许您使用 Carbon/DateTime 对象而不是 CassandraDate 对象。内部,这些日期在保存到数据库时将转换为 CassandraDate 对象。如果您想在非默认日期字段上使用此功能,则需要手动指定,具体操作请参阅此处:https://laravel.net.cn/docs/eloquent#date-mutators
示例
use RoiupAgency\Cassadra\Eloquent\Model as Eloquent; class User extends Eloquent { protected $dates = ['birthday']; }
这允许您执行如下查询
$users = User::where('birthday', '>', new DateTime('-18 years'))->get();
关系
支持的关系包括
- hasOne
- hasMany
- belongsTo
- belongsToMany
- embedsOne
- embedsMany
示例
use RoiupAgency\Cassadra\Eloquent\Model as Eloquent; class User extends Eloquent { public function items() { return $this->hasMany('Item'); } }
以及反向关系
use RoiupAgency\Cassadra\Eloquent\Model as Eloquent; class Item extends Eloquent { public function user() { return $this->belongsTo('User'); } }
belongsToMany 关系不会使用“联合”表,而是将 id 推送到 related_ids 属性。这使得 belongsToMany 方法的第二个参数变得无用。如果您想为关系定义自定义键,请将其设置为 null
use RoiupAgency\Cassadra\Eloquent\Model as Eloquent; class User extends Eloquent { public function groups() { return $this->belongsToMany('Group', null, 'users', 'groups'); } }
其他关系尚不支持,但未来可能会添加。有关这些关系的更多信息,请参阅 https://laravel.net.cn/docs/eloquent#relationships
EmbedsMany 关系
如果您想嵌入模型而不是引用它们,可以使用 embedsMany 关系。此关系类似于 hasMany 关系,但将模型嵌入到父对象中。
请注意:这些关系返回 Eloquent 集合,它们不返回查询构建器对象!
use RoiupAgency\Cassadra\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 方法(自 2.0.0 版本以来可用)更新嵌入的模型
$book = $user->books()->first(); $book->title = 'A Game of Thrones'; $book->save();
您可以通过在关系上使用 destroy 方法或在模型上使用 delete 方法(自 2.0.0 版本以来可用)来删除嵌入的模型
$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 RoiupAgency\Cassadra\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 方法(自 2.0.0 版本以来可用)更新嵌入的模型
$author = $book->author; $author->name = 'Jane Doe'; $author->save();
您可以使用如下方法替换嵌入的模型
$newAuthor = new Author(['name' => 'Jane Doe']); $book->author()->save($newAuthor);
MySQL 关系
如果您使用混合 Cassandra 和 SQL 设置,那真是太幸运了!模型将根据相关模型的类型自动返回 Cassandra-或 SQL-关系。当然,如果您想使此功能双向工作,则您的 SQL 模型需要使用 RoiupAgency\Cassadra\Eloquent\HybridRelations 特性。请注意,此功能仅适用于 hasOne、hasMany 和 belongsTo 关系。
示例 SQL-based User 模型
use RoiupAgency\Cassadra\Eloquent\HybridRelations; class User extends Eloquent { use HybridRelations; protected $connection = 'mysql'; public function messages() { return $this->hasMany('Message'); } }
和基于 Cassandra 的 Message 模型
use RoiupAgency\Cassadra\Eloquent\Model as Eloquent; class Message extends Eloquent { protected $connection = 'cassandra'; public function user() { return $this->belongsTo('User'); } }
原始表达式
这些表达式将直接注入到查询中。
User::whereRaw(['age' => array('$gt' => 30, '$lt' => 40]))->get();
您还可以在内部 CassandraCollection 对象上执行原始表达式。如果在模型类上执行,将返回模型集合。如果在查询构建器上执行,将返回原始响应。
// Returns a collection of User models. $models = User::raw(function($collection) { return $collection->find(); }); // Returns the original CassandraCursor. $cursor = DB::collection('users')->raw(function($collection) { return $collection->find(); });
可选:如果不向原始方法传递闭包,则可以访问内部 CassandraCollection 对象
$model = User::raw()->findOne(['age' => array('$lt' => 18]));
可以通过这种方式访问内部 CassandraClient 和 Cassandra 对象
$client = DB::getCassandraClient(); $db = DB::getCassandra();
Cassandra 特定操作
游标超时
为防止 CassandraCursorTimeout 异常,您可以手动设置一个应用于游标的超时值
DB::collection('users')->timeout(-1)->get();
Upsert
更新或插入一个文档。更新方法的其他选项将直接传递给原生更新方法。
DB::collection('users')->where('name', 'John') ->update($data, ['upsert' => true]);
投影
您可以使用 project 方法将投影应用于查询。
DB::collection('items')->project(['tags' => array('$slice' => 1]))->get();
带有分页的投影
$limit = 25; $projections = ['id', 'name']; DB::collection('items')->paginate($limit, $projections);
Push
向数组中添加项目。
DB::collection('users')->where('name', 'John')->push('items', 'boots'); DB::collection('users')->where('name', 'John')->push('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);
如果您不想重复项目,将第三个参数设置为 true
DB::collection('users')->where('name', 'John')->push('items', 'boots', true);
Pull
从数组中删除项目。
DB::collection('users')->where('name', 'John')->pull('items', 'boots'); DB::collection('users')->where('name', 'John')->pull('messages', ['from' => 'Jane Doe', 'message' => 'Hi John']);
Unset
从文档中删除一个或多个字段。
DB::collection('users')->where('name', 'John')->unset('note');
您还可以在模型上执行 unset 操作。
$user = User::where('name', 'John')->first(); $user->unset('note');
查询缓存
您可以使用 remember 方法轻松缓存查询结果。
$users = User::remember(10)->get();
来源:https://laravel.net.cn/docs/queries#caching-queries
查询日志
默认情况下,Laravel 会记录当前请求中运行的所有查询。然而,在某些情况下,例如插入大量行时,这可能导致应用程序使用过多的内存。要禁用日志,可以使用 disableQueryLog 方法。
DB::connection()->disableQueryLog();