2014-02-25 104 views
0

基本情况如下。一个部分是一个资源蓝图,可以包含多个字段,一个Entry是这个蓝图的记录。Laravel 4雄辩,“动态”关系?

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

我的问题至今: 因此,让我们假设我有一个Field模型,其中场可以有不同的类型,和一个值(内容)。

理想地,动态内容属性将是一个以一对一的关系像

class Field extends Model 
{ 

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

然而,ContentModel类将基于字段的类型值。

每种类型都代表不同的typemodel,它知道如何写它的值(为简单起见,让我们假设有3种类型,inputtextint,和对应的3的模型类ContentInputContentText,和ContentInt

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. 

我在想多态关系,但他们不适合这个特定的情况。

有没有任何有效的方法来实现这一点雄辩?

[EDIT NOTES]

我已经更新如上我是有点不清楚这些实施例。 一种可能的解决方案是根据部分定义动态创建入口模型类。

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 
} 

还不知道这是否是要走的路。

+0

不是一种解决方案,而是稍微类似的:几个月前,我正在玩一个“[脚手架包](https://github.com/nils-werner/laravel-scaffold/blob/master/src/NilsWerner/Scaffold/Managers/FieldManager.php)”,做了某种动态表格布局探测寻找了解哪些列类型在那里。然后它会创建特定字段类型的实例。 –

回答

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

当你可以加载这些关系的解决方案检索字段,然后你可以通过检查哪个内容类型检查3个字段中的哪一个不为空

+0

是的,这是行得通的,实际上,它非常接近我之前提出的解决方案(涉及动态创建模型等)。但是,内容类型应该动态添加,所以字段类无法了解内容类型类。我会更新上面的例子,以获得更精确的整个事情。 – iwyg