samedi 22 octobre 2016

Laravel 5 Join 4 table in eloqent

How can i use larval eloquent model to join 4 table, query from category->sub_category->farm_product->product

I have 4 tables like these

1. categories - id, name (one category has many sub categories)

2. sub_categories - id, category_id, name (one sub category has many farm products)

3. farm_products - id, sub_category_id, name (one farm product has one product)

4. products - id, farm_product_id, name

In my laravel model

1. Category Model

public function sub_category() {
  return $this->hasMany(App\SubCategory);
}

2. SubCategory Model

public function farm_product() {
  return $this->hasMany(App\FarmProduct);
}

3. FarmProduct Model

public function product() {
  return $this->hasOne(App\Products);
}

How I can select category name and select product name which belongs to category

Here is my code but still get error

@foreach(App\Category::all() as $category)
  <p></p>
  //products
  @foreach($category->sub_category->farm_product->product as $products)
    <p></p>
  @endforeach
@endforeach

The output should be

For example :

Category - Fruits Products - App, Orange, Banana

Or should I use another ways, please suggest me

Thank so much.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire