ここに作業バージョンがあります:
移行/データベース
// Blog Categories
Schema::create('categories', function($table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->string('name', 255);
$table->timestamps();
});
// Posts
Schema::create('posts', function($table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('title', 255);
$table->text('body');
$table->timestamps();
$table->foreign('category_id')->references('id')->on('categories');
});
// Fake Data
$category = new Category;
$category->name = 'Category 1';
$category->save();
$category = new Category;
$category->name = 'Category 2';
$category->save();
$post = new Post;
$post->title = 'Blog Post 1';
$post->body = 'Lorem Ipsum';
$post->category_id = 2;
$post->save();
$post = new Post;
$post->title = 'Blog Post 2';
$post->body = 'Lorem Ipsum';
$post->category_id = 1;
$post->save();
投稿モデル
class Post extends Eloquent {
public function Category()
{
return $this->belongs_to('Category','category_id');
}
}
カテゴリ モデル
class Category extends Eloquent {
}
データを取り出しています...
foreach (Post::with('Category')->order_by('created_at', 'desc')->take(10)->get() as $post)
{
echo $post->title."<br/>";
echo $post->body."<br/>";
echo $post->category->name."<br/>";
echo "<br/>\n\n";
}