Laravel在同一张桌子上的几个型号

时间:2014-02-25 17:18:04

标签: laravel laravel-4

我需要一个包含问题和答案的数据库。我想将这些问题和答案放在名为Post的同一个数据库表中。将有一个字段post_type,它告诉我帖子是一个问题或答案。

如何在Laravel模型中实现这一目标?

感谢。

2 个答案:

答案 0 :(得分:9)

您实际需要的是单表继承。您可以在此处找到实现此方法的方法:http://www.colorfultyping.com/single-table-inheritance-in-laravel-4/

基本上,按照此方法,您的object_class表中将有一个名为posts的字段,这就是您所谓的post_type字段,其中包含要在何时进行实例化的模型的类名称选择一个帖子。

使用此方法的好处是,无论您使用哪种方法来检索模型实例(首先,在哪里,查找...),都会实例化正确的类。

例如:

// 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);

答案 1 :(得分:0)

嗯,只需使用Eloquent将模型映射到该表,就像使用任何其他模型>表映射。

然后你可以简单地打电话:

// 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
}

当您插入/添加新帖子时,请确保设置post_type以解决问题或答案。

这一切都很好并且会起作用,但它的编程习惯很糟糕。你真的应该把它分成3个表:Post, Question, Answer并且在三个表之间有关系。