0

i have three tables inventory,products,product_category

in table:inventory

id  product_name  quantity
1      2             24
2      2             54653
3      1             34

here product_name is foreign key..this table has many relation with product table

in table:products

id  name        type_fk_id
1    pc             1
2   laptop          2
3  servo_oil        2

here type_fk_id is foreign key..this table has many relation with product_category table

in table:product_category

id  type_name       
1    PC            
2    oil         
3   servo_oil  

there is no foreign key in product_category table

in my controller

$data=Inventory::all();
return view('inv_view',compact('data'));

in inv_view view

@foreach($data as $inv)
{{$inv->id}}
{{$inv->qty}}

@endforeach

i want to show in the view part also product name and category thats mean

id  quantity   product_name  category
1    34           pc           pc
2    436         servo_oil     oil

i don't know how to access or get this data in view using laravel eloquent relation i know how to use hasmanyThrough in model to access product_category->product->inventory...how can i use inverse of hasmanythrough thats mean inventory->product->product_category

Borna
  • 538
  • 4
  • 19

2 Answers2

2

Try this:

$data=Inventory::with('product.product_category')->get();
return view('inv_view',compact('data'));

Inside View

@foreach($data as $inv)
  {{ $inv->id }}
  {{ $inv->qty }}
  {{ $inv->product->name }}
  {{ $inv->product->product_category->type_name  }}
@endforeach

Define your model relation like below:

App\Inventory

public function product() {
    return $this->belongsTo('App\Product', 'product_name'); 
}

App\Product

public function inventory(){
    return $this->hasMany('App\Inventory');
}

public function product_category() {
    return $this->belongsTo('App\ProductCategory', 'type_fk_id');   
}

App\ProductCategory

public function product() {
    return $this->hasMany('App\Product');   
}

Docs

  • getting this error after using ur code ===RelationNotFoundException in RelationNotFoundException.php line 20: Call to undefined relationship [product] on model [App\Inventory].---------one thing how inventory will know that its foreign key is product_name ????? – Borna Nov 15 '16 at 06:39
  • You need to create relation Inside Inventory model? – Mohammad Nurul Huda Rimon Nov 15 '16 at 06:46
  • can u kindly provide what will be the relation inside inventory??? do u meaning hasmanythrough?? – Borna Nov 15 '16 at 06:50
0

Try to do like this

Join your table with foreign key

$products = DB::table('products')
  ->join('inventory', 'products.id', '=', 'inventory.product_id')
  ->join('product_category', 'products.id', '=', 'product_category.product_id')
  ->select('products.*','product_category.category as category_name')
  ->get(); 
Komal
  • 2,716
  • 3
  • 24
  • 32