Laravel several models on one table

I need a database with questions and answers. I want to put these questions and answers in one database table called Post. There will be a post_type field that tells me that the message is a question or answer.

How can I achieve this in Laravel models?

Thanks.

+7
laravel laravel-4
source share
2 answers

What you are actually looking for is called a single table overlay. You can find a way to implement this here: http://www.colorfultyping.com/single-table-inheritance-in-laravel-4/

Basically, after this method, you will have a field named object_class in your posts table, which you called post_type , which contains the model class name to initiate when you select the message.

The good thing with this method is that any method that you used to extract an instance of the model (first, where, find ...), an instance of the right class will be created.

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); 
+9
source share

Um simply maps the model to this table using Eloquent, as with any other Model> Table mapping.

Then you can simply call:

 // Find the post $post = Post::find(1); // Check if post is question, assuming post_type is boolean/tiny int type if($post->post_type) { // Post is question if post_type is true } else { // Post is an anwser } 

When you insert / add a new message, be sure to set post_type to ask him a question or answer.

This is all good and will work, but it is a poor hands-on programming experience. You really have to divide this into 3 tables: Post, Question, Answer and have a relationship between the three.

0
source share

All Articles