Laravel使用'With'子句将参数从控制器传递给Model

问题描述 投票:0回答:2

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

php laravel laravel-5 eloquent recursive-query
2个回答
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%工作


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;
      }
© www.soinside.com 2019 - 2024. All rights reserved.