【问题标题】:How to build Models for (possibly) polymorphic relationship with Laravel's Eloquent ORM如何使用 Laravel 的 Eloquent ORM 为(可能)多态关系构建模型
【发布时间】:2013-04-06 23:39:20
【问题描述】:

我有一个关于 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 作为外键,我需要明确指定?无论如何,希望你能发现我的困惑并指出我正确的方向。感谢您在我掌握这个问题的过程中提供的高级帮助。

【问题讨论】:

    标签: php database-schema polymorphic-associations laravel-4 eloquent


    【解决方案1】:

    我会勇敢地处理这个并将类型表压缩为一个: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 语句 以确定您是在处理 文章 还是 引用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-29
      • 2015-04-16
      • 2023-02-12
      • 2020-03-25
      • 2016-02-21
      • 1970-01-01
      • 2021-11-17
      • 2016-02-26
      相关资源
      最近更新 更多