2021年1月7日星期四

Laravel 6 eager loading using with() on a belongsTo relationship is only *sometimes* returning null

I am working on a project where we have a model for a service provider, the type of care provided, and the status:

Provider:

class Provider extends Model  {      protected $table = 'providers';        public function status() {          return $this->belongsTo('App\Status');      }        public function caretype() {          return $this->belongsTo('App\CareType', 'id');      }  }  

CareType:

class CareType extends Model  {      protected $table = 'type_of_care';        public function providers() {          return $this->hasMany('App\Providers', 'type_of_care_id');      }        public function category() {          return $this->belongsTo('App\CareCategory');      }  }  

Status:

class Status extends Model  {      protected $table = 'status';        public function providers() {          return $this->hasMany('App\Providers');      }  }  

On the my SearchController (the controller that processes search requests for providers), the show() function using eager loading retrieves the caretype perfectly. But on the search() function that lists the collection of search results, the caretype is always listed as null.

I don't understand why it would be working in one function but not the other, especially when the code to eager load is exactly the same in both functions:

public function search(Request $request)      {            $validated = $request->validate([              //I removed the validation code for this post          ]);            $providers = Provider::with(['status', 'caretype'])->get();            return view('search.results', ['providers' => $providers]);        }        public function show($id)      {            $single_provider = Provider::with(['status', 'caretype'])->where('id', $id)->first();          return view('search.details', ['provider' => $single_provider]);        }  

Any help in this would be appreciated. I know that the model and relationship foreign keys are properly defined because the show() function is able to get the caretype just fine.

https://stackoverflow.com/questions/65622908/laravel-6-eager-loading-using-with-on-a-belongsto-relationship-is-only-someti January 08, 2021 at 11:06AM

没有评论:

发表评论