I had a method:
public function getAllVariants(): HasMany
{
return $this->hasMany(ProductVariant::class, 'product_id', 'id')->with(['product', 'attribute_values', 'image', 'description']);
}
I tried modifying it:
public function getAllVariants(): HasMany
{
$allVariants = $this->hasMany(ProductVariant::class, 'product_id', 'id')->with(['product', 'attribute_values', 'image', 'description']);
if ($allVariants->count() === 0) {
$variantByCode = ProductVariant::where('code', $this->code)->first();
if (!$variantByCode) {
$variants = $this->hasMany(ProductVariant::class, 'product_id', 'id')->where('id', '=', 0);
}
// Retrieve variants related to the product
$allVariants = ProductVariant::where('product_id', $variantByCode->product_id)
->with(['product', 'attribute_values', 'image', 'description']);
}
return $allVariants;
}
This modification is needed to connect product variants with each other. To do this, I changed the product_id query. And I started getting an error:
Blockquote Return value must be of type IlluminateDatabaseEloquentRelationsHasMany, IlluminateDatabaseEloquentBuilder returned
I also want to note that in the future this code will be used as:
$variants = $this->getAllVariants
->each(fn(ProductVariant $variant) => $variant->setRelation('product', $this))
->sortBy('position');
How can I fix the error?