Help us understand the problem. What is going on with this article?

Laravel4, MariaDB, migration

More than 5 years have passed since last update.

Laravel4でdatabase接続を行い、migrationを使ってテーブル作成したり、テーブルから値を取ったりしてみる

OS:Ubuntu14.04
DB:MariaDB 10.0.11 InnoDB
php:5.6.0
thinkpad T440p

MariaDBへの接続設定

laravel_test/app/config/database.phpに設定,mysqlのセクションを変更する
driverはmysql, unix_socketの設定にsockファイルの位置を明記すること
defaultがmysqlになっていること

app/config/database.php
         'default' => 'mysql',
         ・・・ 

        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'larabel_sample',
            'unix_socket' => '/home/user/mariadb_work/tmp/mariadb.sock',
            'username'  => 'hogehoge',
            'password'  => 'fugafuga',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

mariadb側で指定したデータベースを作成しておく

MariaDB [(none)]> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| larabel_sample     |
| my_test            |
| mysql              |
| performance_schema |
| sakila             |
| test               |
+--------------------+

migrationの作成

~/laravel_test$ php artisan migrate:make create_users_table
Created Migration: 2014_09_21_213121_create_users_table
Generating optimized class loader
Compiling common classes
Compiling views

app/database/migrationの下にmigrationファイルができているので修正
function up()とdown()の中を記述

2014_09_21_213121_create_users_table.php
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::create('users', function($table)
        {
            $table->increments('id');
            $table->string('email')->unique();
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::drop('users');
    }

}

migrationの実行

artisan migrateコマンドで実行

~/laravel_test$ php artisan migrate
**************************************
*     Application In Production!     *
**************************************

Do you really wish to run this command? 
Migrated: 2014_09_21_213121_create_users_table

テーブル確認

MariaDB [larabel_sample]> show tables;
+--------------------------+
| Tables_in_larabel_sample |
+--------------------------+
| migrations               |
| users                    |
+--------------------------+
2 rows in set (0.00 sec)

| users | CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  PRIMARY KEY (`id`),
  UNIQUE KEY `users_email_unique` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |

プライマリキーやインデックスの付け方は以下を参考
http://laravel4.kore1server.com/docs/schema
http://laravel.com/docs/schema

foobarテーブルを作ってみる

カラムはfoo,bar,bazの3つ、それぞれint型
primarykeyはfooで(bar,baz)がindexであるようなテーブル

migration作成

~/laravel_test$ php artisan migrate:make create_foobar_table
Created Migration: 2014_09_21_220043_create_foobar_table
Generating optimized class loader
Compiling common classes
Compiling views

定義作成

app/database/schema/***_create_foobar_table.php
・・・
    public function up()
    {
        //
        Schema::create('foobar',function($table)
        {
                $table->integer('foo');
                $table->integer('bar');
                $table->integer('baz');
                $table->primary('foo');
                $table->index(array('bar','baz'));
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
        Schema::drop('foobar');
    }

migrateの実行

~/laravel_test$ php artisan migrate


| foobar | CREATE TABLE `foobar` (
  `foo` int(11) NOT NULL,
  `bar` int(11) NOT NULL,
  `baz` int(11) NOT NULL,
  PRIMARY KEY (`foo`),
  KEY `foobar_bar_baz_index` (`bar`,`baz`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |

ついでにデータを入れておく

MariaDB [larabel_sample]> select * from foobar;
+-----+-----+-----+
| foo | bar | baz |
+-----+-----+-----+
|   1 |   1 |   1 |
|   4 |   1 |   1 |
|   2 |   1 |   3 |
|   3 |   3 |   5 |
+-----+-----+-----+

モデルの作成

デフォルトではidというカラムを主キーとして使用することになっているので
主キーがidでない場合は$primaryKeyを書き換えておくこと

app/models/Foobar.php
pkeyとindexを指定して取ってくる関数を作成
<?php

class Foobar extends Eloquent{

      protected $table = 'foobar';
      protected $primaryKey = 'foo';

      public function get_by_pkey($foo)
      {
    $foobar_rec = $this->where('foo', '=', $foo)->get();
    return $foobar_rec;
      }

      public function get_by_bar_baz($bar,$baz)
      {
    $recs = $this->where('bar','=',$bar)->where('baz','=',$baz)->get();
    return $recs;
      }
}

コントローラの作成

ここではindexの要素を指定して値をとってくる関数を指定
最後のwithはview内で$recsをfoobar_recsとして扱えるようにするという意味

app/controllers/FoobarController.php
<?php

class FoobarController extends BaseController{

      public function get_val($bar=1,$baz=1)
      {
    $FooBarModel = new Foobar;

    $recs = $FooBarModel->get_by_bar_baz($bar,$baz);

    return View::make('foobar/foobar')->with('foobar_recs',$recs);
      }
}

Routeの作成

デフォルト値を使用するパターンと値をURIで指定するパターン
laravel.dev:8080/foobar_look/1/1とかlaravel.dev:8080/foobarでアクセスが出来る
```app/routes.php

Route::get('foobar_look','FoobarController@get_val');
Route::get('foobar_look/{bar}/{baz}','FoobarController@get_val');

//上記二行の代わりに下記のように書いていい
//Route::get('foobar_look/{bar?}/{baz?}','FoobarController@get_val');
```

viewsの作成

view側では渡されたレコードをひとつずつ見ていき、foo(プライマリキー)の値を単に表示するだけ

~/laravel_test/app/views/foobar$ ls
foobar.blade.php  layout.blade.php
foobar.blade.php
@extends('foobar/layout')

@section('content')
    @foreach($foobar_recs as $record)
    <p>{{ $record->foo }} </p>
    @endforeach
@stop
layout.blade.php
<html>
<body>
<h1>FooBarテーブル</h1>

@yield('content')
</body>
</html>

laravel.dev:8080/foobar_look/1/1とかlaravel.dev:8080/foobarでアクセスが出来る

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした