2016-08-24 72 views
0

我是新的Laravel, 我想與條款使用從我的模型控制器通過了$ IDLaravel傳遞參數給模型中使用「與」條款

我的模型

class Menucategory extends Model 
{ 
    protected $fillable = ['title', 'parent_id', 'restaurant_id']; 

    // loads only direct children - 1 level 
    public function children() 
    { 
    return $this->hasMany('App\Menucategory', 'parent_id'); 
    } 

    // recursive, loads all descendants 
    public function childrenRecursive() 
    { 
    return $this->children()->with('childrenRecursive'); 
    } 
} 

我的控制器

public function show($id) 
{ 
    $menucatagories = Menucategory::with('childrenRecursive')->where('restaurant_id',$id)->where('parent_id','0')->get(); 
    return $menucatagories; 
} 

我的當前輸出是

[ 
    { 
    "id": 1, 
    "title": "TestMenu Parant", 
    "parent_id": 0, 
    "restaurant_id": 12, 
    "children_recursive": [ 
     { 
     "id": 2, 
     "title": "TestMenu SubCat1", 
     "parent_id": 1, 
     "restaurant_id": 12, 
     "children_recursive": [ 
      { 
      "id": 6, 
      "title": "TestMenu other sub cat", 
      "parent_id": 2, 
      ******************* 
      "restaurant_id": 13, 
      ******************* 
      "children_recursive": [] 
      }, 
      { 
      "id": 7, 
      "title": "TestMenu other sub cat", 
      "parent_id": 2, 
      "restaurant_id": 12, 
      "children_recursive": [] 
      } 
     ] 
     }, 
     { 
     "id": 3, 
     "title": "TestMenu SubCat2", 
     "parent_id": 1, 
     "restaurant_id": 12, 
     "children_recursive": [] 
     } 
    ] 
    } 
] 

我通過$id=12,但問題是我得到別人restaurant_id的價值在我的孩子陣列,但是,如果我用這個它顯示了正確的jSON

public function childrenRecursive() 
{ 
    $id=12;  
    return $this->children()->with('childrenRecursive')->where('restaurant_id',$id); 
} 

我的問題是如何傳遞的$從控制器到模型的id還是還有其他方法嗎?

回答

0

您可以通過以下方式在控制器本身中設置參數。

 public function show($id) 
    { 
     $menucatagories =Menucategory::with(array('childrenRecursive'=>function($query) use ($id){ 
     $query->select()->where('restaurant_id',$id); 
     })) 
     ->where('restaurant_id',$id)->where('parent_id','0')->get(); 
     return $menucatagories; 
     } 
0

您的childrenRecursive沒有錯。

在這裏看到一個simliar例如:https://stackoverflow.com/a/18600698/2160816

所以我覺得這應該工作

public function childrenRecursive($id = 12){ 
return $this->children()->where('restaurant_id',$id)->with('childrenRecursive'); 
} 

控制器則可以調用

public function show($id) 
{ 
    $menucatagories = Menucategory::where('parent_id','0')->childrenRecursive(12)->get(); 
    return $menucatagories; 
} 

我無法測試它,可能它贏得」 t work 100%

相關問題