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

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

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本