Laravelのマイグレーション、モデル
Laravelでブログアプリを作るにの必要な手順、Laravelの基本を簡単に掲載していきます。
Laravelのディレクトリ構成
・app -> アプリのメインとなる部分
・bootstrap -> 初期処理やキャッシュなど
・config -> アプリの設定
・database -> データベース(マイグレーション)
・public -> 画像、JS、CSSなど
・resources -> bladeなど(HTML的な)
・routes -> アプリのURL設定など
・storage -> セッションやログなど
・tests -> テスト用
・vendor -> Composerの依存内容
マイグレーションとは
・SQLを直接使わなくても、データベースを管理できるLaravelの仕組み
・テーブル作成の流れ
1,マイグレーションファイルを生成
2,ファイルのテーブル定義を書く
3,マイグレーションを実行し、DBに反映
❇︎まずは、1テーブル1ファイルとして覚える
マイグレーションの生成
・マイグレーションファイルを生成する際のコマンド
php artisan make:migration create_blogs_table
カラムを追加する場合は
add_カラム名_to_blogs_table
マイグレーションファイルの中身
・upが実行でdownが元に戻す
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBlogsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('blogs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title', 100);
$table->text('content');
$table->timestamp();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('blogs');
});
}
}
・実行コマンド
php artisan migrate
Eloquent ORMとは?
・Laravelで提供されているデータ操作のための機能。
「モデル」と「DB」を対応づけることができる。
・ORMとはObject Relational Mappingの略で、プログラミング技法のこと
・データベースから取得したデータをオブジェクトとして扱える
Eloquentモデルの作り方
・Artisanコマンド
php artisan make:model モデル名
・モデル名は、テーブル名の単数形にする必要がある
例) blogs => Blog
・他のテーブルと関連させたい時もここで定義できる
実際にモデルを作ってみる
ターミナルで
php artisan make:model Blog
を入力。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
// テーブル名
protected $table = 'blogs';
// 可変項目の値を配列で決める
protected $fillable =
[
'title',
'content'
]
}
モデルを引き継いだBlogというクラスを使えば
blogsテーブルの「title」と「content」のカラムを扱えるBlog.phpにファイルが完成。
おしまい
次は
MVCのルーティングとコントローラーをまとめていきます。
Author And Source
この問題について(Laravelのマイグレーション、モデル), 我々は、より多くの情報をここで見つけました https://qiita.com/hiroto-toyoda/items/13a7e5cfa1e6bc3aadaf著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .