LoginSignup
1
0

More than 5 years have passed since last update.

VaporとMySQLを接続する。その2

Last updated at Posted at 2018-12-05

前回の記事 VaporとMySQLを接続する。その1 ではVaporとMySQLを接続するところまで実装しました。
今回の記事では接続したデータベースの以下のカラムを持つarticleテーブルからデータを取り出していきます。
articleテーブルにはIT企業のエンジニアブログのURLが入っています。(アンテナサイトを作ろうとした時に取得したデータです。アンテナサイトを作ることは半分諦めました)

Field             Type
article_id     int(11)
pub_date date
title   varchar(255)
article_url varchar(45)
site_id   int(11)

articleテーブルに対応するモデルクラス Article.swift を作成します。

Article.swift
import FluentMySQL
import Vapor

final class Article: MySQLModel {
    var id: Int?
    static let entity = "article"  // テーブル名

    var article_id: Int?
    var pub_date: Date?
    var title: String?
    var article_url: String?
    var site_id: Int?
}

extension Article: Migration {}

extension Article: Content { }

extension Article: Parameter { }

作成したモデルクラスのArticle.swiftを使用する旨を configure.swiftで記述します。

configure.swift
/// Configure migrations
var migrations = MigrationConfig()
migrations.add(model: Article.self, database: .mysql)
services.register(migrations)

追記: 本記事と関連する内容の事を書いてくださった方がおりますので紹介します。
本番運用するアプリでモデルの自動マイグレーションを使ってはいけない  

routes.swift/article へのgetリクエストが来たら Article テーブルの内容を返す処理を記述します。
また、Vaporでは Fluent Queries と呼ばれるORMで用いて任意のクエリを発行することができます。

routes.swift
router.get("article") { req in
    return Article.query(on: req).sort(\.pub_date, .descending).range(..<50).all()
}

最後にブラウザから http://localhost:8080/article へアクセスすると以下のようなJSON形式で取得できていることが確認できます。(*実際にはインデントはありません)

[  
   {  
      "article_id":117,
      "pub_date":"2018-09-04T00:00:00Z",
      "title":"運用しているAWS CloudFormationのテンプレートをJSONからYAMLに移行する",
      "site_id":2,
      "article_url":"https:\/\/dev.classmethod.jp\/cloud\/aws\/aws-cloudformation-migration-json-to-yaml\/"
   },
   {  
      "article_id":118,
      "pub_date":"2018-09-04T00:00:00Z",
      "title":"【9\/14(金)大阪】モバイルメソッド大阪 第2回 開催内容決定のお知らせ #mobilemethod",
      "site_id":2,
      "article_url":"https:\/\/dev.classmethod.jp\/event\/mobilemethod_osaka_2\/"
   },
   {  
      "article_id":119,
      "pub_date":"2018-09-04T00:00:00Z",
      "title":"【東京・札幌・大阪】「Alexa Salon vol.3〜Alexa-SDK V2基礎講座&3大VUI試食会〜」を開催します!#Alexa",
      "site_id":2,
      "article_url":"https:\/\/dev.classmethod.jp\/news\/alexa-salon-vol3\/"
   }
   .... 略
]
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0