Gags
Gags

Reputation: 3829

Nested Eloquent Relation - HasOneThrough Issue

I have below setup for tables:

Product_variant Table

Product_variant -> id, name, code, image

Warehouse table

Warehouse -> id, name, address

Product Variant Stock table

Product_Variant_stock -> stock_id, warehouse_id, variant_id, stock_qty

Now, what i need to get information is about in which Warehouse, variant has been stored, when i try to access product variant information.

What i have tried in ProductVariation model:

public function warehouseName()
{
    return $this->hasOneThrough(Warehouse::class, ProductVariantStock::class, 'warehouse_id', 'id');
}

Above is not working as expected. Any help is appreciated.

Upvotes: 1

Views: 171

Answers (1)

rameezmeans
rameezmeans

Reputation: 850

laravel hasOneThrough works like this

class ModelA extends Model
{
    ...
    
    public function cModel()
    {
        return $this->hasOneThrough(
            ModelC::class,
            ModelB::class,
            'model_a_id', // Key on B that relates to A
            'model_c_id', // Key on C that relates to B
            'a_id',       // Key on A that relates to B
            'b_id',       // Key on B that relates to C
        );
    }
}

so your code will be

public function warehouseName()
{
    return $this->hasOneThrough(Warehouse::class, ProductVariantStock::class, 'variant_id', 'id', 'id', 'warehouse_id');
}

Upvotes: 1

Related Questions