rublopweb's avatar

Accessing related models

Hi, i have an endpoint that will receive the id of a database model in the body of the request. I am using the findOrFail method like this $employment =Employment::findOrFail($attributes['employment_id']); but i only need this model to access a related model of a related model so i do not need all the fields, what query should i do to make it all more eficient?

0 likes
7 replies
jaseofspades88's avatar

What have you tried already? If we know the relationships you're trying to improve upon then we might be able to give you a better answet than your vague question warrants.

1 like
rublopweb's avatar

The employment model is related to another model called service, the service is related to the service_timetable and the information i need is a field called weekly_hours which is in the service timetable table. i have done this:

$employment->service->service_schedule()->select('weekly_hours')->get()->first()->weekly_hours;

i would like to optimize it and get only the information i need without retrieving unnecessary information.

Thanks for your help,

1 like
OussamaMater's avatar

@rublopweb, In the query you provided, there is no need for ->get(), this will do the same

$employment->service->service_schedule()->select('weekly_hours')->first()->weekly_hours;

Regarding query optimization, while Laravel offers a fluent API for accessing relationships, it's not mandatory to always use it. Query builders exist for a reason; you can craft your query in SQL and then translate it into a query builder. In this case, I would imaging querying the timetable table directly by providing the related model's ID, selecting only what you need and limiting the result to 1 seems like the way to go approach.

1 like
Snapey's avatar

You are likely optimising for very little gain.

$weekly_hours = 
	Employment::with('service.service_schedule')
		->firstOrFail($attributes['employment_id'])
		->service->service_schedule->weekly_hours;

for this to work, service and service_schedule must be one to one relationships.

1 like
johndivam's avatar
Level 2
$weeklyHours = Employment::with('service.service_schedule')
   ->findOrFail($attributes['employment_id'])
   ->service
   ->service_schedule
   ->value('weekly_hours');
1 like
vincent15000's avatar

If you have solved your problem, please close the post by assigning a best answer.

Please or to participate in this conversation.