如何使用Laravel的Eloquent ORM构建(可能)多态关联的模型

3
我是一名有用的助手,可以为您翻译文本。
我有一个关于Eloquent ORM的问题 - 具体来说,是与Laravel 4一起使用。我在使用它运行基本查询和关系方面没有任何问题,但是我最近遇到了这种有些独特的情况/模式:
我有三个表格。它们的结构目前是这样的:
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

在此之后,我希望只使用Eloquent ORM来运行一个查询/函数,并获取所有帖子及其相应的数据,而不管帖子类型如何。

我很想听听对此的反馈(我的关系、我的模型应该是什么)。据我所知,这可能是一种多态关系。以下是/曾经是我的模型,但我是新手,不确定这是否是正确的方向:

模型: Post.php:

<?php

class Post extends Eloquent {

    public function postType()
    {
        return $this->morphTo();
    }

}

模型:PostTypeArticle.php:

<?php

class PostTypeArticle extends Eloquent {

    public $timestamps = FALSE;
    protected $table = 'post_type_article';

    public function post()
    {
        return $this->morphMany('Post', 'post_type');
    }
}

模型:PostTypeQuote.php:

<?php

class PostTypeQuote extends Eloquent {

    public $timestamps = FALSE;
    protected  $table = 'post_type_quote';

    public function post()
    {
        return $this->morphMany('Post', 'post_type');
    }

}

也许因为我将ENUM作为外键使用,所以需要明确指定?无论如何,希望您能发现我的困惑并指导我走向正确的方向。在我掌握这个技术之前,非常感谢您的帮助。
1个回答

0

对于这个问题,我会勇敢一点,将类型表压缩成一个:post_types:

帖子

    id - int (auto-increment)
    user_id - int (unsigned)
    created_at - timestamp
    updated_at - timestamp

文章类型

    id - int (auto-increment)
    type - int //or varchar
    post_id - int (unsigned)
    title - varchar
    summary- varchar
    url - varchar
    author - varchar
    quote - text

post_types 表中的大多数字段设置为可空 (你的作业)

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'); 
    }

  }

获取结果

$posts = Post::with('postType')->get(); //eager-loading

或者

$post = Post::find(1)->postType; //One post

作业

  1. 使用验证确保数据库中所需的字段均包含在用户输入中
  2. 决定在哪里运行您的if语句以确定您正在处理文章还是引用

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接