doumen9709 2018-12-05 21:16
浏览 136
已采纳

如何将数据插入到不同的表中

I'm using CakePHP to learn about it. I've made a CRUD with relationship, products/categories, in the products form i want to put a field named tags, separated by comma and insert in another table each tag separated. Examples.

Form products (input:tag)

one,two,four

tags (table)

id | product_id | tag
1       2         one
2       2         two

I have no ideia how to do it.

  • 写回答

1条回答 默认 最新

  • doulaopu2343 2018-12-07 19:47
    关注

    What you need to do here is to modify your data before modyfying your entity. Luckily, there is Model.beforeMarshal event, which allows you to do exactly this. A quick and untested example below:

    //put this in your Table class
    public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options){
        if(!empty($data["tag_string"]){
            $tags = explode(", ",$data["tag_string"]);
            $tagsData = [];
            foreach($tags as $tag){
                $tagsData[] = ["tag" => $tag];
            }
            $data["tags"] = $tagsData;
        }
    }
    

    Please note, that I changed tags to tag_string - it's because tags, if you followed CakePHP conventions, will be reserved for your association. Also, by default, your tags will be appended to existing ones, so you need to change your saving strategy with "saveStrategy" => "replace" in your association definition.

    You need also to retrieve your tag string - to do this, you need to create virtual property in your entity:

    //put this in your Entity
    protected function _getTagString(){
        $tagString = "";
        for($i = 0; $i < count($this->tags); $i++){
            $tagString .= $this->tags[$i]->tag;
            if($i != count($this->tags) - 1){
                $tagString .= ", ";
            }
        }
        return $tagString;
    }
    

    With this, you can then retrieve your tag string by calling $product->tag_string.

    More info can be found in CakePHP cookbook:

    Modyfying request data before building entities

    HasMany Association

    Virtual Properties

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C