Laravel - 雄辩的自我关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22824422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:17:45  来源:igfitidea点击:

Laravel - Eloquent Self Relationship

phplaravellaravel-4relationshipeloquent

提问by Marek123

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

我的很多模型和其他代码都在这里并且与这个问题相关:
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.

如果我选择(示例)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,所有子级的 ID 为 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. So I get all from Category 1 and all from 5 (and so on).

我现在需要,如果有人点击主类别,在这种情况下,ID = 1,我可以获得与包括孩子在内的主类别相关的所有食谱。所以我从第 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!

帮助表示赞赏。谢谢!

回答by The Alpha

Depending on the titleand 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 idfield 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 categoriestable should contain primary key idand another field as category_idto make relation so, if an idis 1and if category_idcontains the 1then there is a relation between id=1and category_id=1.

根据这种关系,你的categories表应该包含主键id和另一个字段category_id来建立关系,如果id1,如果category_id包含,1那么id=1和之间存在关系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.

几天前我写了一篇关于同一件事的文章,你可以阅读这篇文章以获得我正在谈论的更好的想法:LARAVEL – 模型与自身的关系