Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 hasMany with WHERE clause

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

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

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

like image 310
kilrizzy Avatar asked Jun 27 '13 20:06

kilrizzy


2 Answers

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

Called with

$menu_items = $menu->menuItems()->where('parent', 0)->get();
like image 84
kilrizzy Avatar answered Oct 30 '22 05:10

kilrizzy


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.

public function menuItems($parent = null){
    if(!$parent == null)){
        $menuItems = $this->hasMany('MenuItem')->where('parent',$parent);
    }else{
        $menuItems = $this->hasMany('MenuItem');
    }
    return $menuItems;
}
like image 44
Rob Avatar answered Oct 30 '22 06:10

Rob