简体   繁体   English

Laravel - 雄辩的自我关系

[英]Laravel - Eloquent Self Relationship

a lot of my models and other code is here and related to this question: 我的很多模型和其他代码都在这里并与此问题相关:
laravel - Query Builder vs. Eloquent laravel - 查询生成器与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. 如果我选择(例子)ID = 5,效果很好。我得到所有食谱,其中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). 比方说,category_id = 5的父级id = 1(主要类别的ID为1-3,所有子级都有4到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. 我现在需要,如果有人点击主要类别,在这种情况下,ID = 1,我可以获得与主要类别相关的所有食谱,包括孩子。 So I get all from Category 1 and all from 5 (and so on). 所以我从第1类获得所有,从5获得所有(依此类推)。

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! 谢谢!

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: 根据您在问题中描述的title和详细信息,我想,您希望使用相同模型的另一个字段/列和id字段创建与模型本身的关系,在这种情况下,您可以使用这样的事情:

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 . 根据这种关系,你的categories表应该包含主键id和另一个字段作为category_id来建立关系,所以,如果id1 ,如果category_id包含1id=1category_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 . 我几天前写过一篇关于同样事情的文章,你可能会读到这篇文章以获得我所说的更好的想法: LARAVEL - 模型与自身的关系

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM