I need a database with Questions and Answers. I want to to put those questions and answers on the same database table named Post. There will be a field post_type, which tell me the post is a question or an answer.
How can I achieve this in Laravel models?
Thanks.
What you are actually looking for is called single table inheritance. You can find a way of implementing this here : http://www.colorfultyping.com/single-table-inheritance-in-laravel-4/
Basically, following this method, you will have a field called object_class
in your posts
table, which is what you called post_type
, containing the class name of the model to instanciate when selecting a post.
The good thing with this method is that whatever method you used to retrieve a model instance (first, where, find...), the right class will be instantiated.
For example :
// this will return an Answer instance (if the class_name is Answer)
$post = Post::find(1);
// which will be the same as
$answer = Answer::find(1);
// and this will return nothing
$question = Question::find(1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With