【问题标题】:how to send variable from controller to model function in laravel如何将变量从控制器发送到laravel中的模型函数
【发布时间】:2017-11-19 20:22:24
【问题描述】:

我想将变量 $typeid 发送到函数类别以在查询中使用它有没有办法知道当我尝试在我的控制器中使用新的类实例时:

 $cat= new Main_category();
 $categories  = $cat->categories()->get();

返回空数组

当我在模型函数中手动添加 typeid 我希望将其作为从控制器发送的变量时,以下代码运行良好

控制器:

$categories  = Main_category::with('categories')->get();

型号

public  function categories()//($typeid) 
{  

     $query = $this->hasMany(Category::class, 'main_cat_id')
              ->join('category_type','category_type.cat_id','=', 'categories.cat_id')                                                   
              ->join('main_categories','main_categories.main_cat_id','=', 'categories.main_cat_id')                                                           
              ->where('category_type.type_id', '1');  // I want to use $typeid here


     return  $query;

}          

【问题讨论】:

    标签: laravel


    【解决方案1】:

    我不确定您是否可以使用with 方法以雄辩的关系方法传递您的变量。但是你可以在控制器中添加 where 子句。

    Main_category::with(['categories' => function($query) use($typeid) {
        $query->where('category_type.type_id', $typeid);
    }])->get();
    

    或者您也可以为模型创建查询范围。

    在模型中

    public function scopeWithCategories($query, $typeid) {
        return $query->with(['categories' => function($query) use($typeid) {
            $query->where('category_type.type_id', $typeid);
        }]);
    }
    

    最后在控制器中

    Main_category::withCategories($typeid)->get();
    

    【讨论】:

      猜你喜欢
      • 2021-11-21
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多