Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel several models on the same table

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.

like image 466
Dau Thanh Hai Avatar asked Feb 25 '14 17:02

Dau Thanh Hai


1 Answers

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);
like image 144
alxscms Avatar answered Oct 25 '22 19:10

alxscms