0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Laravel で MariaDB から MongoDB へデータベースを切り替える

Posted at

Laravel は、MVC なので、Model 部分の変更だけで、データベースを切り替えることが出来ます。
例として、次で作成したものを切り替えてみました。
Laravel で MariaDB の API を作成
MariaDB も、MongoDB も

データベース city
ユーザー scott
パスワード tiger123
として、データの移行はすんでいるとします。

  1. ライブラリーのインストール
composer require jenssegers/mongodb
  1. config/app.php の編集
config/app.php
'providers' => [
// 略
        Jenssegers\Mongodb\MongodbServiceProvider::class,
 ],

    'aliases' => [
// 略
         'Moloquent' => Jenssegers\Mongodb\Eloquent\Model::class,
 ],
  1. .env の編集
.env
DB_CONNECTION=mongodb
DB_PORT=27017
  1. config/database.php の編集
config/database.php
'default' => env('DB_CONNECTION', 'mongodb'),
    // 略
    'connections' => [
        'mongodb' => [
            'driver' => 'mongodb',
            'host' => env('DB_HOST'),
            'port' => env('DB_PORT'),
            'database' => env('DB_DATABASE'),
        'username' => env('DB_USERNAME'),
        'password' => env('DB_PASSWORD'),
        ],
    ],
  1. キャッシュのクリア
php artisan cache:clear
  1. モデルの編集
app/Models/City.php
<?php

namespace App\Models;

class City extends \Moloquent
{
protected $collection = 'saitama';
}
  1. サーバーの起動
php artisan serve --host 0.0.0.0
  1. クライアントでアクセス
curl http://localhost:8000/api/city
curl http://localhost:8000/api/all
curl http://localhost:8000/api/where/岡山
curl http://localhost:8000/api/between/30000/50000
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?