2013-06-27 81 views
5

不确定这是否是将其他查询添加到hasMany参数但不成功的正确方法。这可能吗?Laravel 4 hasMany with WHERE子句

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

当使用

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

叫这完全是在传递一个父返回一个空数组。即使与MenuItem-数据>父= 0存在

我需要某种方式区分我要求我的链接项目“父”,而不是主力车型“父”

+0

你可以发布你的表格布局?我无法分辨这里发生了什么。你的子表只应该有一个对父行的引用。你的' - > hasMany()'从CHILD到PARENT就是引用它的地方。您可能需要提供定义父子关系密钥的第二个参数。 –

回答

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

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

据我所知$ menu-> menuItems()返回一个HasMany实例。无法在HasMany类或其父母中找到where()方法。任何人都知道哪个方法被调用?我很好奇,因为PHPStorm发出警告,说明where方法不存在。 –

+0

在Laravel 5中,直接在关系中附加where子句也是如此: return $ this-> hasMany('MenuItem') - > where('parent',$ parent) - > get(); – mshakeel

+0

这工作正常 – Oussaki

1

我不知道查询部分,但起初不会传递一个0的函数仍将$父变量注册为假?所以也许只是检查$父母是否不为空。

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

称为PHP 0 = FALSE,改变该

如果($父){

如果($父!== FALSE){