I have a question regarding Eloquent ORM -- in this case, specifically being used with Laravel 4. I have had no problem using it to run basic queries and relationships, but I'm recently stumped on this somewhat unique scenario/schema:
I have three tables. Their structures are currently this:
post
id - int
post_type - enum(ARTICLE, QUOTE)
user_id - int
created_at - timestamp
updated_at - timestamp
post_type_article
id - int
post_id - int
title - varchar
summary - varchar
url - varchar
post_type_quote
id - int
post_id = int
author = varchar
quote = text
At the end of this, I would like to just run one query/function using Eloquent ORM and get all posts and their respective data regardless of post_type.
I'd really like to hear some feedback on this (my relationships, what my models should be). From my understanding, this is probably a polymorphic relation. Here are/were my Models, but I am new to this, and am not sure if this the right direction or not:
Model: Post.php:
<?php
class Post extends Eloquent {
public function postType()
{
return $this->morphTo();
}
}
Model: PostTypeArticle.php:
<?php
class PostTypeArticle extends Eloquent {
public $timestamps = FALSE;
protected $table = 'post_type_article';
public function post()
{
return $this->morphMany('Post', 'post_type');
}
}
Model: PostTypeQuote.php:
<?php
class PostTypeQuote extends Eloquent {
public $timestamps = FALSE;
protected $table = 'post_type_quote';
public function post()
{
return $this->morphMany('Post', 'post_type');
}
}
Maybe since I'm using ENUM as a foreign key I need to explicitly specify that? Anyways, hopefully you can spot my confusion and point me in the right direction. Thanks for your help in advanced while I get the hang of this.
I would be brave about this one and condense the types tables into one: post_types:
posts
id - int (auto-increment)
user_id - int (unsigned)
created_at - timestamp
updated_at - timestamp
post_types
id - int (auto-increment)
type - int //or varchar
post_id - int (unsigned)
title - varchar
summary- varchar
url - varchar
author - varchar
quote - text
Make most of the fields in the post_types table nullable (your homework)
Post.php
<?php
class Post extends Eloquent {
public function postType()
{
return $this->hasOne('Posttype'); //or hasMany()
}
}
Posttype.php
<?php
class Posttype extends Eloquent {
protected $table = 'post_types';
public function post()
{
return $this->belongsTo('Post');
}
}
Getting Results
$posts = Post::with('postType')->get(); //eager-loading
OR
$post = Post::find(1)->postType; //One post
Homework