using 3 tables to create calculated custom column in laravel eloquent

  laravel

I am working on some functionality where I have stuck from a long time. I have three tables(I am only mentioning the required fields here):

users: id, date_of_birth (list the registered users)

training: id, start_date (list all the trainings available for which user can register.)

user_training: id, user_id, training_id (store which user registered with which training)

So here I want to query the ‘Users’ eloquent with eager loading with the relation of training and user_training but I need a custom column here named ‘age’ which will calculate the age of the user at the start_date of training. I am using the pagination and I also want to make the age sortable.

Here with joining I can achieve the same but I am wondering if i can do it with just relationship and eager loading. I can add new eloquent relations if required but can not edit the table schema. So I want your advice if it is feasible in this way i.e. without using any joins? Thanks

Source: Laravel

Leave a Reply