簡體   English   中英

如何將變量從控制器發送到laravel中的模型函數

[英]how to send variable from controller to model function in laravel

我想將變量$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;

}          

我不確定是否可以通過with方法在雄辯的關系方法中傳遞變量。 但是您可以在controller中添加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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM