2016-06-21 63 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; 
    } 
} 
相關問題