首页 > 后端开发 > Golang > 正文

使用 Goravel 进行 CRUD 操作 (Laravel for GO)

Linda Hamilton
发布: 2024-10-08 06:14:01
原创
966 人浏览过

CRUD Operations with Goravel (Laravel for GO)

关于Goravel

Goravel是一个功能齐全、扩展性极佳的Web应用框架,作为入门脚手架,帮助Gopher快速构建自己的应用。

Goravel 是针对 Go 开发人员的 Laravel 的完美克隆,这意味着像我这样的 PHP 开发人员可以轻松地与该框架建立联系并开始编写,几乎不需要学习。

下面开始安装,您可以按照本文安装或访问Goravel官方文档网站。

// Download framework
git clone https://github.com/goravel/goravel.git && rm -rf goravel/.git*

// Install dependencies
cd goravel && go mod tidy

// Create .env environment configuration file
cp .env.example .env

// Generate application key
go run . artisan key:generate

//start the application
go run .
登录后复制

在你最喜欢的文本编辑器中打开代码,你会看到项目结构与 Laravel 完全一样,所以 Laravel 开发者不会感到如此迷失。

模型、迁移和控制器

要创建模型、迁移和控制器,我们可以使用 artisan 命令,就像在 Laravel 中一样。

// create model 
go run . artisan make:model Category

// create migration 
go run . artisan make:migration create_categories_table

// create controller 
go run . artisan make:controller --resource category_controller
登录后复制

现在,如果我们检查数据库/迁移文件夹,我们将看到已经为我们创建了文件,向上和向下文件,打开向上迁移文件并将以下代码粘贴到其中:

CREATE TABLE categories (
  id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  name varchar(255) NOT NULL,
  created_at datetime(3) NOT NULL,
  updated_at datetime(3) NOT NULL,
  PRIMARY KEY (id),
  KEY idx_categories_created_at (created_at),
  KEY idx_categories_updated_at (updated_at)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;NGINE = InnoDB DEFAULT CHARSET = utf8mb4;
登录后复制

如果我们检查app/http/controllers文件夹中,我们将有一个category_controller.go文件,里面的内容应该如下所示:

package controllers

import (
 "github.com/goravel/framework/contracts/http"
)

type CategoryController struct {
 //Dependent services
}

func NewCategoryController() *CategoryController {
 return &CategoryController{
  //Inject services
 }
}

func (r *CategoryController) Index(ctx http.Context) http.Response {
 return nil
} 

func (r *CategoryController) Show(ctx http.Context) http.Response {
 return nil
}

func (r *CategoryController) Store(ctx http.Context) http.Response {
 return nil
}

func (r *CategoryController) Update(ctx http.Context) http.Response {
 return nil
}

func (r *CategoryController) Destroy(ctx http.Context) http.Response {
 return nil
}
登录后复制

然后,让我们在 app/http/model 中找到类别模型文件,然后将以下代码粘贴到其中:

package models

import (
 "github.com/goravel/framework/database/orm"
)

type Category struct {
 orm.Model
 Name string
}
登录后复制

这里没有发生什么,我们只是用他们的数据类型声明我们的可填充。

让我们在路由文件夹中找到 api.php 文件并将代码更新为如下所示:

package routes

import (
 "github.com/goravel/framework/facades"

 "goravel/app/http/controllers"
)

func Api() {
 userController := controllers.NewUserController()
 facades.Route().Get("/users/{id}", userController.Show)

 //Resource route
 categoryController := controllers.NewCategoryController()
 facades.Route().Resource("/category", categoryController)
}
登录后复制

现在,让我们更新category_controller.go 文件中的导入并将其更新为以下内容:

import (
 "goravel/app/models"
 "github.com/goravel/framework/contracts/http"
  "github.com/goravel/framework/facades"
)
登录后复制

我们刚刚导入了模型和门面,门面让我们能够访问很多很酷有用的东西,比如验证、orm 等。orm 是 GO 的 ORM。

是时候编写一些代码了!

让我们将控制器中的方法更新为以下代码:

索引方法

// this is just to pull all categories in our database
func (r *CategoryController) Index(ctx http.Context) http.Response {
 var categories []models.Category

 if err := facades.Orm().Query().Find(&categories); err != nil {
  return ctx.Response().Json(http.StatusInternalServerError, http.Json{
   "error": err.Error(),
  })
 }

 return ctx.Response().Success().Json(http.Json{
  "success": true,
  "message": "Data fetch successfully",
  "data":    categories,
 })
} 
登录后复制

储存方法

func (r *CategoryController) Store(ctx http.Context) http.Response {

// validate the input name that the user is passing
 validation, err := facades.Validation().Make(ctx.Request().All(), map[string]string{
        "name": "required|string",
    })

// check if an error occured, might not be validation error
    if err != nil {
        return ctx.Response().Json(http.StatusInternalServerError, http.Json{
            "success": false,
            "message": "Validation setup failed",
            "error":   err.Error(),
        })
    }

// check for validation errors
    if validation.Fails() {
        return ctx.Response().Json(http.StatusBadRequest, http.Json{
            "success": false,
            "message": "Validation failed",
            "errors":  validation.Errors().All(),
        })
    }

// Create the category
 category := &models.Category{
  Name: ctx.Request().Input("name"),
 }

// save the category and return error if there is any
 if err := facades.Orm().Query().Create(category); err != nil {
  return ctx.Response().Json(http.StatusInternalServerError, http.Json{
   "success": false,
   "errors": err.Error(),
  })
 }

// upon successfull creation return success response with the newly created category
 return ctx.Response().Success().Json(http.Json{
  "success": true,
  "message": "Category created successfully",
  "data":    category,
 })
}
登录后复制

更新方法

func (r *CategoryController) Update(ctx http.Context) http.Response {

    validation, err := facades.Validation().Make(ctx.Request().All(), map[string]string{
        "id":   "required",
        "name": "required|string",
    })

    if err != nil {
        return ctx.Response().Json(http.StatusInternalServerError, http.Json{
            "success": false,
            "message": "Validation setup failed",
            "error":   err.Error(),
        })
    }

    if validation.Fails() {
        return ctx.Response().Json(http.StatusBadRequest, http.Json{
            "success": false,
            "message": "Validation failed",
            "errors":  validation.Errors().All(),
        })
    }

// find the category using the id
    var category models.Category
    if err := facades.Orm().Query().Where("id", ctx.Request().Input("id")).First(&category); err != nil {
        return ctx.Response().Json(http.StatusNotFound, http.Json{
            "success": false,
            "message": "Category not found",
        })
    }

// update or return error if there is any
    category.Name = ctx.Request().Input("name")
    if err := facades.Orm().Query().Save(&category); err != nil {
        return ctx.Response().Json(http.StatusInternalServerError, http.Json{
            "success": false,
            "message": "Failed to update category",
            "error":   err.Error(),
        })
    }

// return success if successfull
    return ctx.Response().Success().Json(http.Json{
        "success": true,
        "message": "Category updated successfully",
        "data":    category,
    })
}
登录后复制

销毁方法

func (r *CategoryController) Destroy(ctx http.Context) http.Response {

// find the category by id
 var category models.Category
 facades.Orm().Query().Find(&category, ctx.Request().Input("id"))
 res, err := facades.Orm().Query().Delete(&category)

// return error if there is any
 if err != nil {
  return ctx.Response().Json(http.StatusInternalServerError, http.Json{
  "error": err.Error(),
  })
 }

// return success if successfull
 return ctx.Response().Success().Json(http.Json{
  "success": true,
  "message": "Category deleted successfully",
  "data":    res,
 })
}
登录后复制

现在我们需要设置数据库,我将使用 MySQL,重要的是要注意 Gravel 附带了多个数据库驱动程序。找到您的 .env 文件并编辑以下行:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USERNAME
DB_PASSWORD=DATABASE_PASSWORD
登录后复制

然后在您的终端中输入:

go run . artisan migrate
登录后复制

这将自动迁移数据库中的类别表。

现在,如果您之前正在运行我们的服务器,我们需要停止它并重新启动它。

您现在可以从 Postman 测试您的端点,您应该注意,通过将资源添加到类别端点,您现在可以访问类别端点的 GET、POST、PUT 或 DELETE 方法。您可以通过以下方式访问您的端点:

// GET category
http://localhost:3000/category

//POST catgory - with payload
http://localhost:3000/category
{
    "name": "goravel"
}

// PUT category - with payload
http://localhost:3000/category/{id}
{
    "id": 1,
    "name": "laravel"
}

//DELETE category
http://localhost:3000/category/{id}
登录后复制

这就是如何使用 Goravel 进行简单的 CRUD 操作。

以上是使用 Goravel 进行 CRUD 操作 (Laravel for GO)的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!