public function saveRelatedProducts() { if (!is_array($this->relatedProductsArray)) { $this->relatedProductsArray = explode(',', $this->relatedProductsArray); } $addRelatedProductsArray = (array) $this->relatedProductsArray; foreach ($this->relatedProducts as $product) { $key = array_search($product->id, $addRelatedProductsArray); if ($key === false) { RelatedProduct::deleteAll(['product_id' => $this->id, 'related_product_id' => $product->id]); } else { unset($addRelatedProductsArray[$key]); } } foreach ($addRelatedProductsArray as $relatedProductId) { $relation = new RelatedProduct(); $relation->attributes = ['product_id' => $this->id, 'related_product_id' => $relatedProductId]; $relation->save(); } }
public function saveRelatedProducts() { if (!is_array($this->relatedProductsArray)) { $this->relatedProductsArray = explode(',', $this->relatedProductsArray); } RelatedProduct::deleteAll(['product_id' => $this->id]); foreach ($this->relatedProductsArray as $index => $relatedProductId) { $relation = new RelatedProduct(); $relation->attributes = ['product_id' => $this->id, 'related_product_id' => $relatedProductId, 'sort_order' => $index]; $relation->save(); } }