Laravel使用'使用'将参数从控制器传递到模型。条款

时间:2016-08-24 11:52:06

标签: php laravel laravel-5 eloquent recursive-query

我是Laravel的新人, 我想使用with子句

从模型中的控制器传递$ id

我的模特

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从控制器传递给模型,还是有其他方法?

2 个答案:

答案 0 :(得分:1)

您的childrenRecursive完全没有错。

这里有一个简单的例子: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;
}

我无法测试它,所以它可能不会100%

答案 1 :(得分: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;
      }