Laravel 4.1 impatient download

I'm having problems with impatience. Say I have member models, TrainingCategory, TrainingCategoryResult, and Registration

Member Model:

public function registration() { return $this->hasMany('Registration', 'member_id'); } public function trainingResults(){ return $this->hasMany('trainingResult', 'member_id'); } public function trainingCategoryResults() { return $this->hasMany('TrainingCategoryResult', 'member_id'); } 

Training Model:

 public function trainings() { return $this->hasMany('Training', 'id'); } public function trainingCategoryResults() { return $this->hasMany('trainingCategoryResult', 'category_id'); } 

TraningCategoryResult Model:

  public function category() { return $this->belongsTo('TrainingCategory', 'id'); } public function member() { return $this->belongsTo('Member', 'id'); } 

Registration Model:

  public function course() { return $this->belongsTo('Course', 'course_id'); } public function member() { return $this->belongsTo('Member', 'id'); } 

I am trying to download all registration information and related information, including TraningCategoryResult information, but I'm not sure how to get this TraningCategoryResult that requires two foreign keys (category_id and member_id), is there any way to do this?

Here is my atm code:

  $members= Member::where(function($query) use ($id, $site) { $query ->where('id', '=', $id) ->where('site', '=', $site); }); $members= $members ->with('registration.course', 'registration.course.traningCategories', ->get(['member.id']); 

Thanks.

+6
source share
2 answers

This will not work Member :: with ('categoryResult') → with ('registration') → get ()

You can create a new relationship in the member model.

 public function categoryResult() { return $this->belongsTo('Category')->with('Registration'); } 

// and then call

Member :: with ('categoryResult') → get ();

0
source

You can use several options for this:

OPTION 1 : create a dependency variable

Change your attitude in the member model

 public function trainingCategoryResults($category_id = null) { if(empty($category_id)) return $this->hasMany('TrainingCategoryResult', 'member_id'); else return $this->hasMany('TrainingCategoryResult', 'member_id') ->where('category_id', $category_id); } 

There may be limitations in the above code, and it does not use many laravel functions, but it will work.

OPTION 2: Access from relationship

You can store everything as it is and load as follows:

 $members= Member::where(function($query) use ($id, $site) { $query ->where('id', '=', $id) ->where('site', '=', $site); }) ->where('id', $member_id) // set the id of the memeber ->with(array( 'traningCategoryResults' => function($q)use($category_id){ $q->where('category_id', $category_id); // This makes sure you get only desired results } )) 

This way you will only have what you need if you know that $ category_id

0
source

Source: https://habr.com/ru/post/987570/


All Articles