Laravel 4 hasMany with WHERE 子句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17352888/
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 08:02:33  来源:igfitidea点击:

Laravel 4 hasMany with WHERE clause

laravellaravel-4

提问by kilrizzy

Not sure if this is the correct way to add an additional query to the hasMany argument but was unsuccessful. Is this possible?

不确定这是否是向 hasMany 参数添加附加查询的正确方法,但未成功。这可能吗?

public function menuItems($parent=false){
    if($parent){
        $menuItems = $this->hasMany('MenuItem')->where('parent',$parent);
    }else{
        $menuItems = $this->hasMany('MenuItem');
    }
    return $menuItems;
}

When called using

当使用调用时

$menu_items = $menu->menuItems(0);

This just seems to return an empty array when passed a parent. Even though data with MenuItem->parent = 0 exists

这似乎只是在传递父项时返回一个空数组。即使 MenuItem->parent = 0 的数据存在

Do I need to some way distinguish I'm asking for my linked items "parent" and not the main models "parent"

我是否需要以某种方式区分我要求的链接项目“父”而不是主要模型“父”

回答by kilrizzy

public function menuItems(){
        return $this->hasMany('MenuItem');
}

Called with

$menu_items = $menu->menuItems()->where('parent', 0)->get();

回答by Rob

I am not sure about the query part but at first wouldn't passing a 0 to the function still register the $parent variable as false? So maybe just check if the $parent is not null.

我不确定查询部分,但起初不会将 0 传递给函数仍然将 $parent 变量注册为 false?所以也许只是检查 $parent 是否不为空。

public function menuItems($parent = null){
    if(!$parent == null)){
        $menuItems = $this->hasMany('MenuItem')->where('parent',$parent);
    }else{
        $menuItems = $this->hasMany('MenuItem');
    }
    return $menuItems;
}

回答by MarcoPolo

In PHP 0 = FALSE, change this

在 PHP 中0 = FALSE,改变这个

if( $parent ){

for this

为了这

if( $parent !== false ){