Laravel 4.2 ORM - relation of queries to different tables between

I have a database schema that looks like this:

Section
  id
  name

Subsection
  id
  name
  section_id

Category
  id
  name
  subsection_id

SubCategory
  id
  name
  category_id

Product
  id
  name
  subcategory_id

      

As you can see, each table has a foreign key that refers to the previous table. The problem occurs when I try to get, for example, a section from the current product, or get all products from one section. So far I have tried this:

Section::with('product')->find(1)->product;

      

But I get this:

SQLSTATE [42S22]: Column not found: 1054 Unknown column 'product.section_id' in 'where clause' (SQL: select * from products

, where products

. section_id

In (1))

1 - This makes me think that I need to adjust the section_id in the product table to make this work. It's right?

2 - Shouldn't LARALE ORM automatically lift the table hierarchy from product to section and get results?

3 - Is there a way to do this while maintaining my current table structure, I mean, without adding extra fields to tables for foreign keys?

Thank.

+3


source to share


1 answer


  • No, this is the only way to do it, but it is not the only way.
  • No, how will he know this automatically?
  • I believe so and you can always create a specific request when laravel relationships don't work for you.

Ok, first it is assumed that you have a relationship established for all models in order to access what is underneath. If this is not the case, you will need to establish a relationship.

Section::with('subsection.category.subcategory.product')->get();

      

I've never tried such an extreme nest, but I believe it will work. The Laravel Docs talk about the desired loading and scrolling to see the nested example.



Another element that comes to mind is hasManyThrough. You might not be able to do it for this number, but it might be what you want to learn.

The synopsis from the docs are the first three from your example: section, subsection and category, and then in the section class you should have this relationship.

public function category()
{
    return $this->hasManyThrough('Category', 'SubSection');
}

      

laravel docs with more information.

+2


source







All Articles