1

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.

Gags
  • 3,759
  • 8
  • 49
  • 96

1 Answers1

1

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');
}
rameezmeans
  • 830
  • 1
  • 10
  • 21
  • With this, I am getting message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'warehouses.warehouse_id' in 'on clause' (SQL: select `warehouses`.*, `product_variation_stocks`.`variant_id` as `laravel_through_key` from `warehouses` inner join `product_variation_stocks` on `product_variation_stocks`.`stock_id` = `warehouses`.`warehouse_id` where `product_variation_stocks`.`variant_id` = 1 limit 1)". I then changed warehouse_id to id and then there is no record – Gags Mar 10 '21 at 01:14
  • i just changed the code. i hope it will work. @Gags – rameezmeans Mar 10 '21 at 01:16
  • 1
    nope.. It worked like this return $this->hasOneThrough(Warehouse::class, ProductVariationStock::class, 'variant_id', 'id', 'id', 'warehouse_id'); – Gags Mar 10 '21 at 01:17
  • 1
    Sometimes, it is fun to work with these eloquent complex relationships :).. cheers – Gags Mar 10 '21 at 01:20
  • 1
    yes. if we understand these it is real fun. – rameezmeans Mar 10 '21 at 01:21
  • 1
    It is not this much clear in Laravel documentation as you have explained and we did it.. Thanks – Gags Mar 10 '21 at 01:25