Laravel 5 Eloquent - Add Child Field To Parent Model
I have a user model which has a child relationship called teacher. How can I add a field from the related teacher model to the dataset returned of the parent user model? I would li
Solution 1:
OK, I worked this out myself in the end.
I added a scope to my user model:
publicfunctionscopeJoinWithTeacher($query)
{
return$query->leftJoin("teachers", "teachers.id", "=", "users.userable_id");
}
I then implemented this new scope in my query and aliased columns from child to parent model in the get():
$query = User::where('userable_type', 'App\Teacher');
$query->with('userable');
$query->whereDoesntHave('thisSchool');
$query->JoinWithTeacher();
$query->orderBy( 'distance', 'ASC' );
$otherTeachers = $query->get(['teachers.longitude AS longitude', 'teachers.latitude AS latitude', 'users.*']);
I now have the longitude and latitude columns from the teacher child relation in my parent model returned from eloquent. In my specific case, I then go further to use these alias fields to calculated distance and create a new alias called distance in my user model.
Hope that helps somebody who was attempting the same thing!
K...
Post a Comment for "Laravel 5 Eloquent - Add Child Field To Parent Model"