Laravel findOrFail 与相关数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33456092/
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
Laravel findOrFail with related data?
提问by InvalidSyntax
In my Menu controller I have a method which should display the specified record and all its children.
在我的 Menu 控制器中,我有一个方法可以显示指定的记录及其所有子项。
I have two models: MenuItem
and MenuVariation
, My items will have many variations as outlined in my methods:
我有两个模型:MenuItem
和MenuVariation
,我的项目将有许多变化,如我的方法所述:
MenuItem model
菜单项模型
public function variant()
{
return $this->hasMany('App\MenuVariation');
}
MenuVariation model
菜单变量模型
public function item()
{
return $this->belongsTo('App\MenuItem', 'menu_item_id');
}
Now in my controller I have the following method:
现在在我的控制器中,我有以下方法:
public function show($id)
{
$item = MenuItem::findOrFail($id);
return $item;
}
...which currently only shows the item record but not its variations, so I have changed the code like this...
...目前只显示项目记录但不显示其变体,所以我改变了这样的代码......
public function show($id)
{
$item = MenuItem::findOrFail($id)->with('variant')->get();
return $item;
}
but this oddly return ALL items and their variations.
但这奇怪地返回所有项目及其变体。
Could someone help me get this working as desired? I would like to still utilise FindOrFail on the Item record, but it should also retrieve any variants (if found).
有人可以帮我按需要工作吗?我仍然想在 Item 记录上使用 FindOrFail,但它也应该检索任何变体(如果找到)。
回答by Kirill Fuchs
findOrFail
will initiate the query, so you want to switch the order and put with
in-front of it. Then use findOrFail
. See Below:
findOrFail
将启动查询,因此您要切换顺序并放在with
它的前面。然后使用findOrFail
. 见下文:
public function show($id)
{
$item = MenuItem::with('variant')->findOrFail($id);
return $item;
}
There is also no need for get
when you do that.
get
当你这样做时也没有必要。