Ahmed Abdulrahman
Ahmed Abdulrahman

Reputation: 469

How to use Polymorphic relationship in Laravel 5.3?

I am using laravel 5.3 and I have a scenario as follows

I have 2 models

  1. Robot
  2. Location

A Robot can have many Locations but a location can belong to only 1 Robot, and each time a Robot have a new location the count field in location Table will increment

what I am trying to is that I want to use polymorph relation with Laravel and Eloquent, I want to get all the Locations of all Robots by last updated by using distinct() ?

By the way, Locatable_id in location table is refers to Robot ID. here is my models

Robot Model

public function locations() {
      return $this->morphMany('App\Models\Location', 'locatable');
    }

Location Model

public function locatable() {
      return $this->morphTo();

}

Locations Table

enter image description here

Any help would be really appreciated. Thanks.

Upvotes: 0

Views: 392

Answers (2)

Ahmed Abdulrahman
Ahmed Abdulrahman

Reputation: 469

Here is how I did solve it :)

// Grap all Robots with it's locations and Customer
  $robots = Robot::whereHas('locations', function($query){
    $query->whereNotNull('locatable_id')->orderBy('updated_at');
  })->with('locations')->with('customers')->get();

//Filter only latest Locations for each Robot
  $filterLocations= $robots->map(function($robot){
    $robot->timeEntries = $robot->locations()
      ->orderBy('updated_at', 'DESC')
      ->limit(1)
      ->get();
    return $robot;
  });

Appreciate your spending time for helping out :) Thank you samuele-colombo

Upvotes: 1

Samuele Colombo
Samuele Colombo

Reputation: 685

The query below returns all the robots and for each one provides the latest location. The inner function could be used to filter the locations data.

Robot::with(['locations' => function($q) {
    $q->latest();
}])->get();


what I am trying to is that I want to use polymorph relation with Laravel and Eloquent, I want to get all the Locations of all Robots by last updated by using distinct() ?

This doesn't completely reach your goal but I think that is a good point to start.

Upvotes: 0

Related Questions