jeudi 12 octobre 2017

How to pass parameter from controller to model in case of recursion

My Theme Model

class Theme extends Model
{
    protected $fillable = [
        'level','parent_theme_id','image_url','index_value','status',
    ];
    protected $hidden =[
         'created_at','updated_at','updated_by','created_by',
    ];

       public function themeDetail()
    {
        return $this->hasMany(ThemeDetail::class,'theme_id');
    }

    public function parentTheme()
    {
        return $this->hasMany(Theme::class,'parent_theme_id');
    }

    public function childTheme()
    {
        return $this->belongsTo(Theme::class,'parent_theme_id');
    }

    public function childrenRecursive()
    {
       return $this->childTheme()->with('childrenRecursive');

    }

    public function parentRecursive($request)
    {
       return $this->parentTheme()->with(['themeDetail' => function($query) use($request){
        $query->whereIn('language_code',array('en',$request->language_code));
       }])->parentRecursive($request);
    }

 }


My themeDetail Model

class ThemeDetail extends Model
{
    protected $fillable = [
        'theme_id','language_code','theme_name','theme_subtitle','status',
    ];
    protected $hidden =[
         'created_at','updated_at','updated_by','created_by',
    ];

        public function theme()
    {
        return $this->belongsTo(Theme::class);
    }
}


And My Theme Controller

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Theme;

class ThemeController extends Controller
{
    public function theme(Request $request){
        $theme_detail = Theme::with(['themeDetail' => function($query) use($request){
            $query->whereIn('language_code',array('en',$request->language_code));
        },**'parentRecursive'**])->whereNull('parent_theme_id')->get();
        if($theme_detail->isNotEmpty()){
            return response()->json(['status' => 'success','message' => 'Theme List with Detail','theme_detail' => $theme_detail], 200);
        }else{
            return response()->json(['status' => 'not-found','message' => 'Theme List with Detail'], 205);
        }

    }

}


Here I have used a recursive relation for fetching theme and subthemes in a tree like structure.

Now I want to send a parameter '$request->language_code' through the parentRecursive relation (which is highlighted in my query) of Theme controller to parentRecursive relation of Theme model.

So, what is the correct syntax to pass the parameter from controller to model for this case? Please Help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire