人生の恥は書き捨て

プログラムとかいろいろ

【Laravel入門】モデルとリレーション

モデルとリレーション

今回言っているモデルというのはlaravelのeloquent機能の話です。
データベースにArticlesというテーブルがあることを仮定します。

準備

tableはmigarateを使って作ります。

<?php

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

class CreateArticleTable extends Migration {

	/**
	 * Run the migrations.
	 *
	 * @return void
	 */
	public function up()
	{
		Schema::create('articles', function($table)
        {   
            $table->increments('id');
            $table->string('title', 20);
            $table->text('contents');
            $table->timestamps();
        });
	}

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

}

eloquentモデルの基本操作

次にモデルファイルapp/models/article.phpを作ります。

<?php

class Article extends Eloquent{
	
}

Laravelだと、これだけでもうデータベースへのアクセスができるようになります。
例えば

<?php
$articles = Article::all();

で全件取得ができます。

<?php
$first_article = Article::find(1);

でid=1のarticleが取得できます。

クエリービルダーのメソッドを使ってより詳細な操作ができます。

<?php
$article = Article::where('title', 'article_title')->first();

とすると、titleがarticle_titleであるarticleのうち最初の1件が取得できます。

クエリービルダーのメソッドの詳しい使い方はここに書いてあります。
DB:クエリービルダー

リレーション

articleにはカテゴリーがあって、
一つのカテゴリーに複数のarticleが所属していると考えます。

categoryもmigrateで作ります。

<?php

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

class CreateCategoryTable extends Migration {

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

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

}

次にカテゴリーのモデルを作ります。

<?php

class Category extends Eloquent{
	
}

で、カテゴリーが複数のarticleを持っているので、
カテゴリーから見てarticleはhasManyで、articleから見てカテゴリーはbelongsToです。
それぞれの設定をモデルに書いていきます。

category.php

<?php

class Category extends Eloquent{
	public function article(){
		return $this->hasMany('Article');
	}
}


article.php

<?php

class Article extends Eloquent{
	public function category(){
		return $this->belongsTo('Category');
	}
}

これだけです。

Articleから自分の所属しているカテゴリーを取得したいときは、

<?php
Article::find(1)->category

のようにして取得します。

おわりに

LaravelのEloquentは思った以上に書くことがなくて簡単でした。
あと、リレーションはCakeとかFuelだと専用の設定みたいなのに書きますが、
Laravelだと普通にメソッドとして書くのがちょっと新鮮でした。
こっちのほうが使いやすい気がします。