加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – 关系设计

发布时间:2020-12-13 16:56:09 所属栏目:PHP教程 来源:网络整理
导读:我正在构建一个应用程序,客户可以从预定义的模板创建文档,使用自己的文本编辑某些字段并保存.我已经勾勒出了我认为的关系,并且转换成Laravel是最好的: 我唯一的问题是我如何处理FieldValue关系.我们的想法是模板定义所有字段,然后不是在每个文档上重新创建
我正在构建一个应用程序,客户可以从预定义的模板创建文档,使用自己的文本编辑某些字段并保存.我已经勾勒出了我认为的关系,并且转换成Laravel是最好的:

我唯一的问题是我如何处理FieldValue关系.我们的想法是模板定义所有字段,然后不是在每个文档上重新创建它们,它应该只为它们的模板查找.这意味着FieldValue需要查看其Document,其模板,并从那里找到相应的Field.

有没有一种干净的方法来实现这一点,还是有更好的方法来设计关系,使其更实用?

解决方法

按照图表,看起来像一个带有透视数据的数据透视表……

在Laravel中通常会这样建模:

class Document extends Model
{
    public function template()
    {
        return $this->belongsTo('AppTemplate');
    }

    public function fields()
    {
        return $this->belongsToMany('AppField')->withPivot('value');
    }
}

class Template extends Model
{
    public function organisation()
    {
        return $this->belongsTo('AppOrganisation');
    }

    public function documents()
    {
        return $this->hasMany('AppDocument');
    }

    public function fields()
    {
        return $this->hasManyThrough('AppField','AppSection');
    }

    public function sections()
    {
        return $this->hasMany('AppSection');
    }
}

class Section extends Model
{
    public function fields()
    {
        return $this->hasMany('AppDocument')->withPivot('value');
    }

    public function template()
    {
        return $this->belongsTo('AppTemplate');
    }
}

class Field extends Model
{
    public function documents()
    {
        return $this->belongsToMany('AppDocument')->withPivot('value');
    }

    public function section()
    {
        return $this->belongsTo('AppSection');
    }
}

class Organisation extends Model
{
    public function documents()
    {
        return $this->hasManyThrough('AppDocument','AppTemplate');
    }

    public function templates()
    {
        return $this->hasMany('AppTemplate');
    }
}

使用相关表格(如果坚持使用laravel默认值):

fields
    id - integer
    section_id - integer

documents
    id - integer
    template_id - integer

templates
    id - integer
    organisation_id - integer

sections
    id - integer
    template_id - integer

organisations
    id - integer

document_field
    id - integer
    document_id - integer
    field_id - integer
    value - string

然后你可以通过许多不同的方式访问.这是一个例子:

$user = AppUser::find(3);

$organisation = $user->organisation;

foreach ($organisation->documents as $document)
{
    foreach ($document->fields as $field)
    {
        echo $field->pivot->value;
    }
}

并插入:

$field = AppField::find(2);

$document = AppDocument::find(4);

$value = 'My field value';

$document->fields()->save($field,['value' => $value]);

相关文档:

> Many-to-many relationships
> Querying relationships
> Inserting related models
> Working with pivot tables

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读