代码之家  ›  专栏  ›  技术社区  ›  mewc

CakePHP保存有许多关联

  •  0
  • mewc  · 技术社区  · 7 年前

    我有一个产品需要将图像路径保存到另一个表。 product hasMany images .

    add()

    if ($this->request->is('post')) {
        // https://book.cakephp.org/3.0/en/orm/saving-data.html#saving-associations
        $save = $this->Products->newEntity(
            $this->request->getData(),
            ['associated'=>$associated]
        );
    
        $this->log('JUST AFTER PATCH'.$save);
        $save->last_modified = Time::now();
        $save->created = Time::now();
    
        //sort out assoc.
        $path = $this->saveImageGetPath($this->request->data['images']);
    
        $save['images'][] = [
            'path' => $path,
            'alt_description' => $product->name . Time::now() . 'img',
            'position' => $this->request->data['position']
        ];
    
        $save->isDirty(true);
        $this->log('JUST BEFORE SAVE'.$save);
        if ($this->Products->save($save, [
            'associated'=> ['Shoes', 'Images', 'Products_has_categories']
        ])) {
    

    这是到日志的阵列输出

    {
        "name":"xlc",
        "brands_id":1,
        "description":"csvfd",
        "type":"s",
        "position":"0",
        "shoe":{
            "heels_id":1,
            "closures_id":1,
            "materials_upper_id":1,
            "materials_lining_id":1,
            "materials_sole_id":1
        },
        "products_has_categories":{
            "categories_id":"1"
        },
        "images":[
            {
                "path":"\/webroot\/img\/products\/img1503289958.jpg",
                "alt_description":"8\/21\/17, 4:32 AMimg",
                "position":"0"
            }
        ],
        "last_modified":"2017-08-21T04:32:38+00:00",
        "created":"2017-08-21T04:32:38+00:00"
    }
    

    这是桌子 Image 协会。

    $this->hasMany('Images', [
        'foreignKey' => 'products_id',
        'dependent' => true,
    ]);
    

    图像上传很好,你可以得到路径。它只是没有为此触发SQL语句,我不知道为什么 hasOne assoc.确实有效,所以我可以保存assoc.但不能用这个 hasMany

    1 回复  |  直到 7 年前
        1
  •  1
  •   ndm    7 年前

    如果你将图像作为数组添加到数据中,那将不起作用,ORM将只保存实体对象,即你必须创建一个 \Cake\Datasource\EntityInterface 相反(实体创建/修补过程将自动为传递的数据执行此操作)。

    $save['images'][] = $this->Products->Images->newEntity([
        'path' => $path,
        'alt_description' => $product->name . Time::now() . 'img',
        'position' => $this->request->data['position']
    ]);
    

    此外,您需要确保 images 属性被标记为脏,否则ORM将忽略它(这也是在实体创建/修补过程中自动完成的)。你的 isDirty(true) 电话什么也做不了,因为 isDirty() 不是二传手,而是获得者。

    $save->setDirty('images', true); // use dirty('images', true) in CakePHP < 3.4
    

    此外,您最好使用 debug() var_export() 相反,为了保留实体提供的调试信息。