-
Notifications
You must be signed in to change notification settings - Fork 56
6.1 Product Variations
It might still not clear for you, what product variation actually is.
But variation is actually something useful for the modern e-commerce, as for each product you may have, you will have it with different properties such as colors , height, width and so on. this is where the variation takes place.
unconsciously we used the variation in the previous section while using the fetchByVariations method, as it uses the method we are going to explore at the moment.
here is a snippet of the unit-test, to clarify it to you.
public function setUp() {
parent::setUp();
$this->variationRepo = app('ProductVariationRepository');
}
/** @test */
public function it_retrieves_filtered_variations() {
$product = factory(Product::class)->create();
$type = factory(ProductVariationType::class)->create([
'product_id' => $product->id,
'stock' => 30,
]);
$anotherType = factory(ProductVariationType::class)->create([
'product_id' => $product->id,
'stock' => 50,
]);
$variation = factory(ProductVariation::class)->create([
'product_variation_type_id' => $type->id,
'product_id' => $product->id,
]);
factory(ProductVariation::class)->create([
'product_variation_type_id' => $anotherType->id,
'product_id' => $product->id,
'details' => ['color' => 'red', 'size' => 'XL'],
]);
// partially matching.
$this->assertCount(2, $this->variationRepo->contains($product->types, ['color' => 'green', 'size' => 'XL']));
// does not match at all.
$this->assertCount(0, $this->variationRepo->contains($product->types, ['color' => 'green', 'size' => 'L']));
}
as the comments mention out, if It's partially matching still you can get results, but you actually can decide whether you really need the partially matching part or not by passing the third parameter.
the contain method accepts 3 parameters
- Instance of Collection/Builder
- Attributes we are searching for ( array )
- Include Partials or not ( Boolean ) , that's set to true by default.
If the first argument being passed as an instance of builder, we will join the product_variations with the products table where the product_variations.product_id is equal to products.id then filter the retrieved variations depending on the passed attributes in the second argument.
The collection passed to this method should be a collection of SecTheater\Marketplace\Models\EloquentProductVariationType
Then we will pluck the ids and search within the ProductVariation for the matched records, and filter through the variations depending on the passed attributes in the second argument.