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_type 是什么。

我真的很想听听对此的一些反馈(我的关系,我的模型应该是什么)。据我了解,这可能是一种多态关系。这是/是我的模型,但我对此并不陌生,并且不确定这是否正确:

型号: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 作为外键我需要明确指定?无论如何,希望你能发现我的困惑并指出我正确的方向。感谢您在我掌握这一点时提供的高级帮助。

4

1 回答 1

0

我会对此很勇敢,并将类型表压缩为一个:post_types:

帖子

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

post_types

    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 语句以确定您是在处理文章还是引用
于 2013-06-12T10:08:12.173 回答