Laravel 4雄辩,“充满活力”的关系?

时间:2014-02-25 22:24:01

标签: laravel-4 eloquent

基本上情况如下。一个部分是一个资源蓝图,可以包含多个字段,一个条目是该蓝图的记录。

class Entry extends Model
{
    public function section()
    {
        return $this->hasOne('Section');
    }
}

到目前为止我的问题: 所以我们假设我有一个Field模型,其中字段可以有不同的类型和一个值(其内容)。

理想情况下,动态内容属性是一对一的关系,如

class Field extends Model
{

    public function content()
    {
        return $this->hasOne('ContentModel');
    }
}

但是,ContentModel类将基于字段的类型值。

每种类型代表一种不同的类型模型,它知道如何编写其值(为简单起见,我们假设有3种类型,inputtextint和相应的3个模型类ContentInputContentTextContentInt

sections (Section)
- id (char, 36) // uuid
- label (varchar)
- handle (varchar)


entries (Section)
- id (char, 36) // uuid
- section_id (char, 36) // uuid of the section


fields (Field)
- id (integer)
- section_id (char, 36) // uuid of the section
- type (varchar) // the content model class
- handle (varchar)
- label (varchar)


content_input (ContentInput)
- id
- entry_id (char, 36) // entry record of a section 
- field_id (integer)
- value (varchar)


content_text (ContentText)
- id
- entry_id (char, 36) // entry record of a section
- field_id (integer)
- value (text)


content_int (ContentInt)
- id
- entry_id (char, 36) // entry record of a section
- field_id (integer)
- value (integer)

// ... there're many more content types. 

我在考虑多态关系,但它们不适合这种特殊情况。

有没有有效的方法来实现这一目标?

[编辑说明]

我已经更新了上面的例子,因为我有点不清楚。 一种可能的解决方案是根据节定义动态创建条目模型类。

class Entry_249fcb61_4253_47d5_80ab_e012e19e7727 extends Entry
{
    protected $with = ['gettext', 'getinput', 'getint'];  

    public function gettext()
    {
        return $this->hasMany('ContentText', 'entry_id');
    }

    // and so on
}

仍然不知道这是否可行。

1 个答案:

答案 0 :(得分:0)

可能有更好的方法,但这里是我想出的类似问题的解决方案

fields (Field)
- id
- inputId -> nullable -> default = null
- textId -> nullable -> default = null
- intId -> nullable -> default = null

Field.php

public function input()
    {
        return $this->hasOne('Content_input', 'id', 'inputId');
    }

public function text()
    {
        return $this->hasOne('Content_text', 'id', 'textId');
    }

public function integer()
    {
        return $this->hasOne('Content_int', 'id', 'intId');
    }

您可以在检索Field时加载这些关系,然后通过检查3个字段中的哪个不为空来检查每个内容类型