wim91's avatar

How to get data from related tables in reverse order?

I have a table "Categories" and "Subcategories". The table "Subcategories" is related to the table "Categories" by a one-to-one relationship. So each subcategory is tied to a specific category.

In the model "Subcategories" I created hasOne()

public function getCategory()
{
return $this->hasOne(CategoryEvent::class,'id','category_id');
}

In the model "Categories" I created belongsTo()

public function thisSubCategory()
{
return $this->belongsTo(SubCategory::class, 'id');
}

Now when accessing "Category" I want to get a collection of all "Subcategories" by relationship. Is it possible?

I tried this:

Category::with('thisSubCategory')->get();

I only have the last entry from the "Subcategory" in relations. Please help.

0 likes
3 replies
Glukinho's avatar

The table "Subcategories" is related to the table "Categories" by a one-to-one relationship

This seems to be wrong, I think you should make your relations vice versa:

  • Category -> HasMany -> Subcategory
  • Subcategory -> BelongsTo -> Category

Table subcategories has column category_id which refers to table category.

After that you'll be able to fetch subcategories of a category:

$category      = Category::find(123);
$subcategories = $category->subcategories; // collection

As another option, haven't you considered to have categories and subcategories in one table, with column parent_id referring to the same table? It's more complicated structure, but doable, there are packages implementing it. In your current structure you can't have subcategory of a subcategory (you are bound to only 2 levels of categories).

1 like
wim91's avatar

@Glukinho Oh! Exactly! Thanks, I fixed everything, after 8 hours of coding I don't notice the obvious anymore! Regarding your suggestion, I'm not very good at organizing a database, and besides, there are other tables that refer to these, I'm just giving a simple example, for brevity and clarity, in reality I have more complex connections and uploads.

Please or to participate in this conversation.