andyharis / yii2apigql
Yii2 API gql
0.2.5
2018-06-26 09:47 UTC
Requires
- yiisoft/yii2: ^2
README
yii2-apigql 提供了进行 CRUD 操作与数据库交互的方法
用法
例如,我们有 3 个表/模型:Users,Messages,Post。
Users-> hasManyPostPost-> hasManyMessages
我们想访问包含帖子的所有消息的客户
{
"username": "",
"avatarUrl": "",
"post": {
"postName":"",
"messages": {
"textMessage": "",
"dateAdded": ""
}
}
}
发起请求并获取您提供格式的所有数据。
GET /clients?select={"username": "","avatarUrl": "","post": {"postName": "","messages": {"textMessage": "","dateAdded": ""}}}
// response { "username": "Andyhar", "avatarUrl": "http://example.com/andyhar.png", "post": [ { "postName": "Post about API", "dateAdded": "1500276204", "messages": [ { "textMessage": "Hey what a nice post!", "dateAdded": "1500276704", }, { "textMessage": "Make more posts like this!", "dateAdded": "1500279841", } ] }, ] }
- 通过一个查询访问主模型和嵌套关系数据。
- 按嵌套关系排序
/clients?select={...}&sort=post.postName- 按升序排序post.postName ASC/clients?select={...}&sort=!post.messages.dateAdded- 按降序排序post.messages.dateAdded DESC
- 使用嵌套条件过滤数据
/clients?select={"username":"=Andyhar"}- 其中username 等于 Andyhar/clients?select={"post":{"messages":{"textMessage":"~Rocks"}}}- 其中post.messages.textMessage like Rocks/clients?select={"post":{"likes":">35"}}- 其中post.likes > 35
安装
安装此扩展的首选方式是通过 composer。运行以下命令之一:
composer require andyharis/yii2apigql
入门指南
安装后,您应在配置文件中启用此模块扩展
- 打开您的
frontend/config/main.php - 将模块
gql添加到bootstrap部分
// main.php return [ 'id' => 'app-frontend', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log', 'gql'], // your code ];
然后您需要初始化组件本身。只需将新的组件 gql 添加到您的组件列表中即可。
// main.php 'components' => [ 'gql' => [ 'class' => "andyharis\yii2apigql\Bootstrap", 'relations' => require 'models.php' ], // your code ]
创建文件 models.php
如您所见,我们 require 'models.php' 以让组件知道应使用哪些模型。
因此,您可能想为这种情况创建一个单独的文件来存储您的模型。
// models.php use andyharis\yii2apigql\components\api\Relations; // Initializing component relations class which will handle dependencies $object = new Relations(); // Add all models you need to work with $object ->addModel(String $name, String $className) ... ... ->addModel('clients', \frontend\models\Clients::className()) ->addModel('job', \frontend\models\Job::className()); // we need to return this object with relations return $object;
在哪里
clients- 表示模型的名称\frontend\models\Clients::className()- 表示用于获取和更新数据的模型
几乎完成了
另一件重要的事情是使用 Yii2ApigqlRecord 组件扩展所有模型。
// frontend/models/Clients.php namespace frontend\models; use andyharis\yii2apigql\components\Yii2ApigqlRecord; // This is important, because Yii2ApigqlRecord has some methods which use your models to make magic. // Of course you can extend it with your class but don't forget to extend Yii2ApigqlRecord class Clients extends Yii2ApigqlRecord
就这样。现在您可以使用 yii2apigql 进行操作。
有关更多信息,请访问 Wiki 以获取 API 文档。