从一个后端/构建器表单中种植多个表?

时间:2018-03-25 13:26:35

标签: php laravel octobercms

我试图从一个(构建器)后端表单/模型中将数据插入到多个相关表中 - 但似乎我做错了。

t1帖子(用于模型Posts.php)

id, flag1, flag2 , created_at, updated_at

t2 post_content(用于模型Posts_content.php)

id, content

我已经尝试扩展用于表单的模型(Posts.php),如octobercms的关系文档中所解释的那样:

public $hasOne = ['content' => ['Test\Gcn\Models\Post_content', 'key' => 'id', 'otherKey' => 'id']];

虽然通过后端控制器创建记录时不会产生错误,但实际上没有数据写入posts_content。

我也试图用代理字段来解决它

fields.yaml(模型Posts.php)

post_content[content]:
label: 'Post here'
size: ''
mode: tab
span: full
type: markdown

Posts.php(带代理字段)

public function formExtendModel($model)
{
    /*
     * Init proxy field model if we are creating the model
     */
    if ($this->action == 'create') {
        $model->post_content = new Post_content;
    }
    return $model;
}

根据错误消息,需要将数组设置为jsonable。但即便如此,它似乎试图将数据插入错误的表格中。

实现这一目标的正确方法是什么? 我尝试使用一个表单,用户可以输入一些标记(复选框等)和一个文本字段,该字段应插入到具有正确ID的post_content表中。

感谢您的时间和帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

From my opinion, you have to do many changes in your structure like below:

1) Add content_id in your posts table

id, flag1, flag2, content_id, created_at, updated_at

And second table should be contents table

id, content

content_id will be used to create one to one relationship between Post and Content. For more information about relations click here.

2) Then, you have to define models Post for posts and Content for all contents.

In Content model give One to one relationship.

public $hasOne = [
        'post' => 'Test\Gcn\Models\Post'
    ];

If you give this type of relation, this will find content_id in your Post model so it set direct relationship between Post and Content.

3) Your form field should be like

In Post model fields.yaml should be

fields:
    flag1:
        label: 'Flag 1'
        oc.commentPosition: ''
        span: left
        type: text
    flag2:
        label: 'Flag 2'
        oc.commentPosition: ''
        span: auto
        type: text

And In Content model fields.yaml should be

fields:
    post:
        label: Post
        oc.commentPosition: ''
        nameFrom: flag1
        descriptionFrom: description
        span: auto
        type: relation
    content:
        label: Content
        size: small
        oc.commentPosition: ''
        span: left
        type: textarea

and columns.yaml should be

columns:
    content:
        label: Content
        type: text
        searchable: true
        sortable: true
    post:
        label: Post
        select: flag1
        relation: post
        searchable: true
        sortable: true

For more details about the backend, you can go here...1) form relation 2) column relation.

This all is from my side. Now analyze all this and try your code. And tell me if you have any query.

Thank you.