2016-06-21 82 views
1

我制作了一个模块,如果它不存在,我会自动将产品添加到Prestashop。PHP - Prestashop将多个图像添加到单个产品中

我已在此事上关注this主题,并设法在添加产品时使用该图像。但问题是当我遇到有多个图像的产品时。

我试图使其重复此过程为每个图像的foreach循环内把它包起来:

foreach ($image_arr as $image_val) { 
    $image = new Image(); 
    $image->id_product = $product->id; 
    $image->position = Image::getHighestPosition($product->id) + 1; 
    $image->cover = true; // or false; 
    if (($image->validateFields(false, true)) === true && 
     ($image->validateFieldsLang(false, true)) === true && $image->add()) 
    { 
     $image->associateTo($product->id_shop_default); 
     if (!copyImg($product->id, $image->id, $image_val, 'products', false)) 
     { 
      $image->delete(); 
     } 
    } 
} 

但它不工作。它会在ps_image上引发重复错误

任何想法如何使它工作?

回答

0

您不能将所有图像覆盖属性设置为true

这里是ps_image表设置相关指标:

_________________________________________ 
| Name    | Unique | Column  | 
|_________________________________________| 
| id_product_cover | Yes | id_product | 
|     |  | cover  | 
| idx_product_image | Yes | id_image | 
|     |  | id_product | 
|     |  | cover  | 
|-----------------------------------------| 

应该有每个产品只有一个盖子。

你可以改变你的代码是这样的:

$cover = true; 
foreach ($image_arr as $image_val) { 
    $image = new Image(); 
    $image->id_product = $product->id; 
    $image->position = Image::getHighestPosition($product->id) + 1; 
    $image->cover = $cover; 
    if (($image->validateFields(false, true)) === true && 
     ($image->validateFieldsLang(false, true)) === true && $image->add()) 
    { 
     $image->associateTo($product->id_shop_default); 
     if (!copyImg($product->id, $image->id, $image_val, 'products', false)) 
     { 
      $image->delete(); 
     } 
    } 

    if ($cover) 
    { 
     $cover = false; 
    } 
} 
相关问题