Laravel - Eloquent Self Relationship

17,658

Depending on the title and details you described in your question makes me think that, you want to create a relationship to the model itself using another field/column of the same model and the id field and in this case you may create such a relationship using something like this:

class Category extends Eloquent {

    public function recipes()
    {
        return $this->hasMany('Category', 'category_id');
    }

}

According to this relationship, your categories table should contain primary key id and another field as category_id to make relation so, if an id is 1 and if category_id contains the 1 then there is a relation between id=1 and category_id=1.

I've written an article a few days ago on this same thing, you may read that to get the better idea that I'm talking about: LARAVEL – MODEL RELATIONSHIP TO ITSELF.

Share:
17,658
Marek123
Author by

Marek123

Updated on June 20, 2022

Comments

  • Marek123
    Marek123 almost 2 years

    a lot of my models and other code is here and related to this question:
    laravel - Query Builder vs. Eloquent

    I have this query:

            $recipes = Recipe::whereHas('categories', function($q) use ($cat_id) {
            $q->where('category_id', $cat_id);
        })->with('user')->get();  
    

    Works great if I choose (example) ID = 5. I get all recipes which have category_id = 5.

    What if...
    Let's say, the category_id = 5 has the parent with the id = 1 (Main categories have ID 1-3 and all children have 4 to x).

    I need now, that if someone clicks the main category, in this case, ID = 1, that I can get ALL recipes that are related to the main category including the children. So I get all from Category 1 and all from 5 (and so on).

    I have NO clue, how I can set the relationship or built the query.

    Second is, that I also need to implement this function into the "advanced search" method of the website, but I think, if I can solve this question, the rest is "easy".

    Help is appreciated. Thank you!

  • Marek123
    Marek123 about 10 years
    The relationship is already there. I have a parent_category and child_categories methods, so this is fine. I need to select all related categories including the main category in my sql statement or Eloquent / Query .
  • The Alpha
    The Alpha about 10 years
    That's exactly I've answered, id is the parent and category_id is the child items, did you read the article ? You should read that to get the idea, I've used it in a similar thing.