ulobby / neoeloquent
Laravel 对 Neo4j 图数据库 REST 接口的包装
Requires
- php: >=7.4
- ext-json: *
- illuminate/console: ^10.0|^11.0
- illuminate/database: ^10.0|^11.0
- illuminate/events: ^10.0|^11.0
- illuminate/pagination: ^10.0|^11.0
- illuminate/support: ^10.0|^11.0
- laudis/neo4j-php-client: ^2.4
Requires (Dev)
- guzzlehttp/guzzle: ^7.0
- mockery/mockery: ^1.4.2
- phpunit/phpunit: ^9.3.3
- symfony/var-dumper: *
Replaces
- vinelab/neoeloquent: 1.4.7
- dev-master
- v9.5.1
- v9.5.0
- v9.4.1
- v9.4.0
- v9.3.0
- v9.2.0
- v9.1.0
- v9.0.6
- v9.0.5
- v9.0.4
- v9.0.3
- v9.0.2
- v9.0.1
- v9.0.0
- v8.0.1
- v8.0.0
- 7.0.x-dev
- v7.0.1
- v7.0.0
- v6.2.1
- v6.2.0
- v6.1.0
- 6.0.x-dev
- v6.0.1
- v6.0
- v1.4.8
- v1.4.7
- dev-support-laravel11
- dev-fix-multiple-whereRelation
- dev-neo4j-v4
- dev-neo4j-v4-support
- dev-add-flag-to-see-original-exception
- dev-improve-error-messages
- dev-cast-timeout
- dev-some-fixes
- dev-expose-raw-results
- dev-new-driver-using-helper
- dev-extend-from-illuminate-classes
- dev-several-fixes
- dev-switch-client-2
- dev-switch-client
- dev-main
- dev-update-from-vinelab
- dev-php8-allow-failures
- dev-remove-timestamps-from-relationships
This package is auto-updated.
Last update: 2024-09-27 14:28:54 UTC
README
NeoEloquent
Neo4j 图 Eloquent 驱动程序 for Laravel,这是由 Vinelab/NeoEloquent 创建的,并由 Ulobby 分支。
如果您是 NeoEloquent 的初学者,我们建议您使用和贡献原始仓库 - 但当然,如果您仍然想使用我们的分支并提交 PR,您当然可以自由使用。
此存储库的版本方案遵循 Laravel,因此此包的主版本号对应于支持 Laravel 的主版本号。例如,NeoEloquent v6 支持 Laravel v6,NeoEloquent v8 支持 Laravel v8。
在 Ulobby,我们在基于 Laravel 的 SaaS 中使用 NeoEloquent 进行许多 CRUD 操作。通常,我们会为更复杂操作编写原始 cypher,因此我们目前不建议使用多态关系。
聊天 & 支持
加入 官方 Neo4j Slack Group 并使用 #neo4j-php 频道。
快速参考
安装
将包添加到您的 composer.json
并运行 composer update
。
Laravel 8
8.0
{ "require": { "ulobby/neoeloquent": "^8.0" } }
Laravel 7
7.0
{ "require": { "ulobby/neoeloquent": "^7.0" } }
Laravel 6
6.0
{ "require": { "ulobby/neoeloquent": "^6.0" } }
在 app/config/app.php
中添加服务提供者
'Vinelab\NeoEloquent\NeoEloquentServiceProvider',
服务提供者将注册此包所需的所有类,并将 Model
类别别名为 NeoEloquent
,因此您可以在模型中简单地 扩展 NeoEloquent
。
配置
连接
在 app/config/database.php
中或根据基于环境的配置在 app/config/[env]/database.php
中,将 neo4j
设置为默认连接
'default' => 'neo4j',
添加连接默认值
'connections' => [ 'neo4j' => [ 'driver' => 'neo4j', 'host' => env('DB_HOST', 'localhost'), 'port' => env('DB_PORT', '7474'), 'username' => env('DB_USERNAME', null), 'password' => env('DB_PASSWORD', null) ] ]
迁移设置
如果您想使用迁移
- 创建文件夹
app/database/labels
- 修改
composer.json
并将app/database/labels
添加到classmap
数组 - 运行
composer dump-autoload
文档
模型
class User extends NeoEloquent {}
NeoEloquent 与其简单性一样,将根据类名生成默认节点标签,在这种情况下,它将是 :User
。有关节点标签的更多信息,请参阅 节点标签
命名空间模型
当您在模型中使用命名空间时,标签将考虑完整的命名空间。
namespace Vinelab\Cms; class Admin extends NeoEloquent { }
从该关系生成的标签将是 VinelabCmsAdmin
,这是为了确保在引入另一个 Admin
实例(如 Vinelab\Blog\Admin
)时标签不会冲突,这会在数据库中的 :Admin
上造成混乱。
自定义节点标签
您可以指定要使用的标签(而不是默认生成的),它们也是区分大小写的,因此将按此处存储的方式存储。
class User extends NeoEloquent { protected $label = 'User'; // or array('User', 'Fan') protected $fillable = ['name', 'email']; } $user = User::create(['name' => 'Some Name', 'email' => 'some@email.com']);
NeoEloquent 对 $table
变量的回退支持,如果找到并且模型上未定义 $label
,则将使用它。
class User extends NeoEloquent { protected $table = 'User'; }
不要担心标签的格式化,您可以将它们指定为 array('Label1', 'Label2')
或通过冒号分隔,并在前面添加冒号是可选的。
软删除
Laravel 5
要启用软删除,您需要使用 Vinelab\NeoEloquent\Eloquent\SoftDeletes
而不是 Illuminate\Database\Eloquent\SoftDeletes
,并且和 Eloquent 一样,您需要在模型中包含 $dates
,如下所示
use Vinelab\NeoEloquent\Eloquent\SoftDeletes; class User extends NeoEloquent { use SoftDeletes; protected $dates = ['deleted_at']; }
关系
让我们通过一些节点之间关系示例来了解。
一对一
class User extends NeoEloquent { public function phone() { return $this->hasOne('Phone'); }
这表示从 :User
节点到 :Phone
节点的 OUTGOING
关系方向。
保存
$phone = new Phone(['code' => 961, 'number' => '98765432']) $relation = $user->phone()->save($phone);
此语句执行的 Cypher 语句如下
MATCH (user:`User`)
WHERE id(user) = 1
CREATE (user)-[:PHONE]->(phone:`Phone` {code: 961, number: '98765432', created_at: 7543788, updated_at: 7543788})
RETURN phone;
定义此关系的逆关系
class Phone extends NeoEloquent { public function user() { return $this->belongsTo('User'); } }
这表示从 :User
节点到此 :Phone
节点的 INCOMING
关系方向。
关联模型
由于我们不处理 外键,在我们的例子中,这不仅仅是设置父模型的 foreign key 属性。在 Neo4j(以及图形数据库)中,关系本身就是一个实体,也可以有自己的属性,因此引入了 边
注意:关联模型在调用
associate()
时不会自动持久化关系。
$account = Account::find(1986); // $relation will be Vinelab\NeoEloquent\Eloquent\Edges\EdgeIn $relation = $user->account()->associate($account); // Save the relation $relation->save();
此语句执行的 Cypher 语句如下
MATCH (account:`Account`), (user:`User`)
WHERE id(account) = 1986 AND id(user) = 9862
MERGE (account)<-[rel_user_account:ACCOUNT]-(user)
RETURN rel_user_account;
一对多
class User extends NeoEloquent { public function posts() { return $this->hasMany('Post', 'POSTED'); } }
这表示从 :User
节点到 :Post
节点的 OUTGOING
关系方向。
$user = User::find(1); $post = new Post(['title' => 'The Title', 'body' => 'Hot Body']); $user->posts()->save($post);
类似于 一对一
关系,save()
语句返回的值是一个 Edge[In|Out]
此语句执行的 Cypher 语句如下
MATCH (user:`User`)
WHERE id(user) = 1
CREATE (user)-[rel_user_post:POSTED]->(post:`Post` {title: 'The Title', body: 'Hot Body', created_at: '15-05-2014', updated_at: '15-05-2014'})
RETURN rel_user_post;
定义此关系的逆关系
class Post extends NeoEloquent { public function author() { return $this->belongsTo('User', 'POSTED'); } }
这表示从 :User
节点到此 :Post
节点的 INCOMING
关系方向。
多对多
class User extends NeoEloquent { public function followers() { return $this->belongsToMany('User', 'FOLLOWS'); } }
这表示一个 :User
节点与另一个 :User
节点之间的 INCOMING
关系。
$jd = User::find(1012); $mc = User::find(1013);
$jd
跟随 $mc
$jd->followers()->save($mc);
或者使用 attach()
方法
$jd->followers()->attach($mc); // Or.. $jd->followers()->attach(1013); // 1013 being the id of $mc ($mc->getKey())
此语句执行的 Cypher 语句如下
MATCH (user:`User`), (followers:`User`)
WHERE id(user) = 1012 AND id(followers) = 1013
CREATE (followers)-[:FOLLOWS]->(user)
RETURN rel_follows;
$mc
反过来跟随 $jd
$mc->followers()->save($jd);
此语句执行的 Cypher 语句如下
MATCH (user:`User`), (followers:`User`)
WHERE id(user) = 1013 AND id(followers) = 1012
CREATE (user)-[rel_user_followers:FOLLOWS]->(followers)
RETURN rel_follows;
获取 $jd
的粉丝
$followers = $jd->followers;
此语句执行的 Cypher 语句如下
MATCH (user:`User`), (followers:`User`), (user)-[rel_user_followers:FOLLOWS]-(followers)
WHERE id(user) = 1012
RETURN rel_follows;
动态属性
class Phone extends NeoEloquent { public function user() { return $this->belongsTo('User'); } } $phone = Phone::find(1006); $user = $phone->user; // or getting an attribute out of the related model $name = $phone->user->name;
多态
多态关系的概念与骨结构纯粹相关,但在图形数据库中,我们将其表示为 超边。
超边涉及三个模型,即 父 模型、超 模型和 相关 模型,如下图所示
在代码中,这将以三个模型 User
、Comment
和 Post
来表示,其中 id 为 1 的 User
发布了一个 Post
,而 id 为 6 的 User
在那个 Post
上发表了一个 Comment
,如下所示
class User extends NeoEloquent { public function comments($morph = null) { return $this->hyperMorph($morph, 'Comment', 'COMMENTED', 'ON'); } }
为了使事情保持简单但仍然涉及三个模型,我们不得不传递 $morph
,它可以是任何 commentable
模型,在我们的例子中,它可以是 Video
或 Post
模型。
注意:请确保将其默认设置为
null
,这样我们稍后就可以动态或懒加载$user->comments
。
使用 create()
方法创建一个 Comment
。
$user = User::find(6); $post = Post::find(2); $user->comments($post)->create(['text' => 'Totally agree!', 'likes' => 0, 'abuse' => 0]);
和往常一样,我们将返回一个边,但这次它不是有方向的,它是一个 HyperEdge
实例,更多关于 超边 的信息。
或者您也可以保存一个 Comment 实例
$comment = new Comment(['text' => 'Magnificent', 'likes' => 0, 'abuse' => 0]); $user->comments($post)->save($comment);
还支持所有在 BelongsToMany
关系中找到的功能,如通过 Ids 关联模型
$user->comments($post)->attach([$id, $otherId]);
或解除模型关联
$user->comments($post)->detach($comment); // or $comment->id
同步
$user->comments($post)->sync([$id, $otherId, $someId]);
检索多态关系
从我们之前的示例中,我们将使用 Video
模型来检索它们的评论
class Video extends NeoEloquent { public function comments() { return $this->morphMany('Comment', 'ON'); } }
动态加载多态模型
$video = Video::find(3); $comments = $video->comments;
懒加载多态模型
$video = Video::with('comments')->find(3); foreach ($video->comments as $comment) { // }
检索多态关系的逆关系
class Comment extends NeoEloquent { public function commentable() { return $this->morphTo(); } }
$postComment = Comment::find(7); $post = $comment->commentable; $videoComment = Comment::find(5); $video = $comment->commentable; // You can also eager load them Comment::with('commentable')->get();
您还可以指定返回的 morph 类型
class Comment extends NeoEloquent { public function post() { return $this->morphTo('Post', 'ON'); } public function video() { return $this->morphTo('Video', 'ON'); } }
多态关系简述
为了深入探讨,以下是参与多态关系的三个模型如何连接
class User extends NeoEloquent { public function comments($morph = null) { return $this->hyperMorph($morph, 'Comment', 'COMMENTED', 'ON'); } }
class Post extends NeoEloquent { // Video is the same as this one public function comments() { return $this->morphMany('Comment', 'ON'); } }
class Comment extends NeoEloquent { public function commentable() { return $this->morphTo(); } }
懒加载
class Book extends NeoEloquent { public function author() { return $this->belongsTo('Author'); } }
以尽可能少的性能开销加载作者及其书籍。
foreach (Book::with('author')->get() as $book) { echo $book->author->name; }
循环中仅运行两个 Cypher 查询
MATCH (book:`Book`) RETURN *;
MATCH (book:`Book`), (book)<-[:WROTE]-(author:`Author`) WHERE id(book) IN [1, 2, 3, 4, 5, ...] RETURN book, author;
边
简介
由于图中的关系与其它数据库类型有很大的不同,因此我们需要相应地处理它们。关系有方向,可以分别指向父节点的入和出方向。
EdgeIn
表示从相关模型指向父模型的INCOMING
方向关系。
class Location extends NeoEloquent { public function user() { return $this->belongsTo('User', 'LOCATED_AT'); } }
要将User
关联到Location
$location = Location::find(1922); $user = User::find(3876); $relation = $location->associate($user);
在Cypher世界中,它映射为(:Location)<-[:LOCATED_AT]-(:User)
,其中$relation
是一个代表指向父节点的入关系的EdgeIn
实例。
并且您仍然可以从边访问模型
$relation = $location->associate($user); $location = $relation->parent(); $user = $relation->related();
EdgeOut
表示从父模型指向相关模型的OUTGOING
方向关系。
class User extends NeoEloquent { public function posts() { return $this->hasMany('Post', 'POSTED'); } }
要保存从:User
到:Post
的出边,它看起来是这样的
$post = new Post(['...']); $posted = $user->posts()->save($post);
在Cypher中,这将表示为(:User)-[:POSTED]->(:Post)
,其中$posted
是EdgeOut
实例。
并获取相关模型
$edge = $user->posts()->save($post); $user = $edge->parent(); $post = $edge->related();
HyperEdge
此边是作为多态关系的结果出现的,表示涉及两个其他边(左和右)的边,可以通过left()
和right()
方法访问。
此边与其他边略有不同,因为它不是两个模型之间的直接关系,这意味着它没有特定的方向。
$edge = $user->comments($post)->attach($comment); // Access the left and right edges $left = $edge->left(); $user = $left->parent(); $comment = $left->related(); $right = $edge->right(); $comment = $right->parent(); $post = $right->related();
处理边
如前所述,与SQL中的外键不同,边是图中的实体,在文档中它们要么是嵌入,要么是引用的id。因此,我们开发了它们,让它们成为轻量级模型,这意味着您可以像处理Eloquent
实例一样处理它们——在一定程度上,除了超边之外。
// Create a new relationship $relation = $location->associate($user); // Vinelab\NeoEloquent\Eloquent\Edges\EdgeIn // Save the relationship to the database $relation->save(); // true
对于HyperEdge
,您可以通过以下方式访问所有三个模型
$edge = $user->comments($post)->save($comment); $user = $edge->parent(); $comment = $edge->hyper(); $post = $edge->related();
边属性
默认情况下,边将自动设置并更新时间戳created_at
和updated_at
,前提是已通过将父模型上的$timestamps
设置为true
启用时间戳。
$located_at = $location->associate($user); $located_at->since = 1966; $located_at->present = true; $located_at->save(); // $created_at and $updated_at are Carbon\Carbon instances $created_at = $located_at->created_at; $updated_at = $located_at->updated_at;
从关系检索边
与创建关联的方式相同,我们可以在调用关联上的belongsTo
关系中的edge($model)
方法时检索两个模型之间的边。
$location = Location::find(1892); $edge = $location->user()->edge();
您还可以指定边另一侧的模型。
注意:默认情况下,NeoEloquent将尝试执行内部
$location->user
以根据关系函数名称确定边的相关侧,在这种情况下是user()
。
$location = Location::find(1892); $edge = $location->user()->edge($location->user);
仅在 Neo 中
在这里,您会发现NeoEloquent特定的方法和实现,它们与Eloquent的奇妙方法结合使用,可以使处理图和Neo4j变得非常愉快!
创建With
此方法将“某种程度上”填补了关系数据库和文档数据库之间的差距,它允许在一次数据库调用中创建多个相关模型。
创建新记录和关系
以下是一个创建带有附件照片和视频的帖子的示例
class Post extends NeoEloquent { public function photos() { return $this->hasMany('Photo', 'PHOTO'); } public function videos() { return $this->hasMany('Video', 'VIDEO'); } }
Post::createWith(['title' => 'the title', 'body' => 'the body'], [ 'photos' => [ [ 'url' => 'http://url', 'caption' => '...', 'metadata' => '...' ], [ 'url' => 'http://other.url', 'caption' => 'the bay', 'metadata' => '...' ] ], 'videos' => [ 'title' => 'Boats passing us by', 'description' => '...' ] ]);
键
photos
和videos
必须与Post
模型中的关系方法名称相同。
上述示例执行了以下Cypher查询
CREATE (post:`Post` {title: 'the title', body: 'the body'}),
(post)-[:PHOTO]->(:`Photo` {url: 'http://url', caption: '...', metadata: '...'}),
(post)-[:PHOTO]->(:`Photo` {url: 'http://other', caption: 'the bay', metadata: '...'}),
(post)-[:VIDEO]->(:`Video` {title: 'Boats passing us by', description: '...'});
我们将以以下方式获取创建的节点及其关系
您还可以混合模型和属性作为关系值,但这是不必要的,因为NeoEloquent将通过$fillable
过滤器管道传递提供的属性。
$videos = new Video(['title' => 'foo', 'description' => 'bar']); Post::createWith($info, compact('videos'));
您还可以使用单个数组作为属性
class User extends NeoEloquent { public function account() { return $this->hasOne('Account'); } } User::createWith(['name' => 'foo'], ['account' => ['guid' => 'bar', 'email' => 'some@mail.net']]);
将现有记录作为关系附加
createWith
足够智能,可以知道当您传递现有模型、模型ID或需要创建的新记录时之间的区别,这允许混合新记录和现有记录。
class Post extends NeoEloquent { public function tags() { return $this->hasMany('Tag', 'TAG'); } }
$tag1 = Tag::create(['title' => 'php']); $tag2 = Tag::create(['title' => 'dev']); $post = Post::createWith(['title' => 'foo', 'body' => 'bar'], ['tags' => [$tag1, $tag2]]);
我们将得到与现有Tag
节点相关的Post
。
或使用模型的id
Post::createWith(['title' => 'foo', 'body' => 'bar'], ['tags' => 1, 'privacy' => 2]);
关联记录的查询Cypher语句为:
CREATE (post:`Post` {title: 'foo', 'body' => 'bar'})
WITH post
MATCH (tag:`Tag`)
WHERE id(tag) IN [1, 2]
CREATE (post)-[:TAG]->(tag);
迁移
要使迁移正常工作,请执行以下操作:
- 创建文件夹
app/database/labels
- 修改
composer.json
并将app/database/labels
添加到classmap
数组
由于Neo4j是一个无模式数据库,您不需要预先定义标签的属性类型。然而,您可以使用NeoEloquent的简单索引和约束。
命令
NeoEloquent在neo4j
命名空间下引入了新的命令,因此您仍然可以并行使用Eloquent的迁移命令。
迁移命令与Eloquent相同,格式为neo4j:migrate[:command]
neo4j:make:migration Create a new migration file
neo4j:migrate Run the database migrations
neo4j:migrate:reset Rollback all database migrations
neo4j:migrate:refresh Reset and re-run all migrations
neo4j:migrate:rollback Rollback the last database migration
创建迁移
与Laravel类似,您可以使用Artisan的make
命令创建一个新的迁移。
php artisan neo4j:migrate:make create_user_label
标签迁移将放置在app/database/labels
您可以为命令添加额外的选项,例如
php artisan neo4j:migrate:make foo --path=app/labels
php artisan neo4j:migrate:make create_user_label --create=User
php artisan neo4j:migrate:make create_user_label --label=User
运行迁移
运行所有挂起的迁移
php artisan neo4j:migrate
运行特定路径的所有挂起迁移
php artisan neo4j:migrate --path=app/foo/labels
运行特定包的所有挂起迁移
php artisan neo4j:migrate --package=vendor/package
注意:如果在运行迁移时收到“类未找到”错误,请尝试运行
composer dump-autoload
命令。
在生产环境中强制运行迁移
要强制在生产数据库上运行迁移,可以使用
php artisan neo4j:migrate --force
回滚迁移
回滚最后一个迁移操作
php artisan neo4j:migrate:rollback
回滚所有迁移
php artisan neo4j:migrate:reset
回滚所有迁移并重新运行它们
php artisan neo4j:migrate:refresh
php artisan neo4j:migrate:refresh --seed
模式
NeoEloquent将自动将Neo4jSchema
外观别名化,以便您可以在操作标签时使用。
Neo4jSchema::label('User', function(Blueprint $label) { $label->unique('uuid'); });
如果您决定手动编写迁移类(不使用生成器),请确保有这些use
语句
use Vinelab\NeoEloquent\Schema\Blueprint;
use Vinelab\NeoEloquent\Migrations\Migration;
目前Neo4j支持UNIQUE
约束和INDEX
属性。您可以在以下位置了解更多信息:
http://docs.neo4j.org/chunked/stable/graphdb-neo4j-schema.html
模式方法
删除标签
Neo4jSchema::drop('User'); Neo4jSchema::dropIfExists('User');
重命名标签
Neo4jSchema::renameLabel($from, $to);
检查标签是否存在
if (Neo4jSchema::hasLabel('User')) { } else { }
检查关系是否存在
if (Neo4jSchema::hasRelation('FRIEND_OF')) { } else { }
您可以在以下位置了解更多关于迁移和模式的信息:
https://laravel.net.cn/docs/schema
https://laravel.net.cn/docs/migrations
聚合
除了Eloquent构建器聚合外,NeoEloquent还支持Neo4j特定的聚合,如percentile和standard deviation,以保持相同的函数名以方便使用。请查看文档以获取更多信息。
table()
代表模型的标签
$users = DB::table('User')->count();
$distinct = DB::table('User')->countDistinct('points');
$price = DB::table('Order')->max('price');
$price = DB::table('Order')->min('price');
$price = DB::table('Order')->avg('price');
$total = DB::table('User')->sum('votes');
$disc = DB::table('User')->percentileDisc('votes', 0.2);
$cont = DB::table('User')->percentileCont('votes', 0.8);
$deviation = DB::table('User')->stdev('sex');
$population = DB::table('User')->stdevp('sex');
$emails = DB::table('User')->collect('email');
变更日志
请查看发布以获取详细信息。
避免
以下是一些约束和图特定的注意事项,这是一些既不受支持也不推荐的功能列表。
连接 😖
- 它们对于图没有意义,图也讨厌它们!这使得它们故意不受支持。如果您从基于
SQL
的应用程序迁移,它们将是您的噩梦。
多对多关系中的交叉表
这不受支持,我们将使用边来处理模型之间的关系。
嵌套数组和对象
- 由于单个对象映射类型存储的限制,您不能在单个模型中拥有嵌套的数组或对象,请确保它是扁平的。示例:
// Don't User::create(['name' => 'Some Name', 'location' => ['lat' => 123, 'lng'=> -123 ] ]);
请查看createWith()方法了解如何在图形方式中实现此功能。
测试
- 安装Neo4j实例并使用默认配置
localhost:7474
运行它 - 确保数据库图是空的,以避免冲突
- 运行
composer install
后,应该有/vendor/bin/phpunit
- 在确保Neo4j实例正在运行后,运行
./vendor/bin/phpunit
标记为未完成的测试意味着它们可能是已知问题或不受支持的特性,请查看包含的消息获取更多信息。