Pergunta

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!

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top