CakePHP Saving有很多关联

时间:2017-08-21 04:41:22

标签: php cakephp orm associations cakephp-3.x

我的产品需要将图像路径保存到另一个表格。 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 assoc。

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

图片上传正常,您可以获得路径。它只是没有为此触发SQL语句,我很困惑为什么 请注意,hasOne个关联。确实有效,所以我可以保存关联。但不是这个hasMany

1 个答案:

答案 0 :(得分:1)

您将图像作为数组添加到数据中,不会起作用,ORM只会保存实体对象,即您必须创建\Cake\Datasource\EntityInterface的实例(&& #39; s实体创建/修补过程将自动为传递的数据做什么。)

$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()来代替记录JSON表示,以保留实体提供的调试信息。

另见