1
votes

I have problem with eloquent query. I am using eager loading (one-to-many Polymorphic Relationship) to sortby 'historyable.date', JSON below.

[
   {
      "product_id":12,
      "product_name": "Product C",
      "historyable_type":"App\\Delivery",
      "historyable":{
         "id":2,
         "date":"0303\/0404\/2020",
         "for":"Customer A",
         "created_at":"2020-04-02T09:46:48.000000Z",
      }
   },
   {
      "product_id":1,
      "product_name": "Product A",
      "historyable_type":"App\\Transfer",
      "historyable":{
         "id":1,
         "date":"0202\/0404\/2020",
         "for":"First Balance ****",
         "created_at":"2020-04-02T07:30:45.000000Z",
      }
   },
   {
      "product_id":11,
      "product_name": "Product B",
      "historyable_type":"App\\Delivery",
      "historyable":{
         "id":2,
         "date":"0303\/0404\/2020",
         "for":"Customer B",
         "created_at":"2020-04-02T09:46:48.000000Z",
      }
   }
]

And i try to get result like this

[
   {
      "product_id":1,
      "product_name": "Product A",
   },
   {
      "product_id":12,
      "product_name": "Product C",
   },
   {
      "product_id":11,
      "product_name": "Product B",
   }
]

Is it possible to run with Nested Lazy Eager Loading Laravel?

Product Model

public function track() {
   return $this->hasMany('App\History');
}

History Model

public function historyable(){
   return $this->morphTo()->orderBy('date', 'desc');
}

Product Controller

public function json_history(Product $product) {
   $data = $product->with('track.historyable')
   ->where('id', $product->id)
   ->first();
   return $data->track;
}

I Have database like this

Products Table
#id
#name

Histories Table
#product_id
#product_name
#historyable_id
#historyable_type

Deliveries Table
#id
#date
#for

Transfers Table
#id
#date
#for
1
plz post your code.TsaiKoga
Post your code in order for us to help you.rkg
Thanks Ahead, I just added my code..Guna Wirawan

1 Answers

0
votes
public function json_history(Product $product) {
   $data = Product::with('track.historyable')
           ->where('id', $product->id)
           ->first();

   $arr = $data->track->toArray();

   $date = array();
   $create = array();
   foreach ($arr as $key => $row)
   {
      $date[$key]  = $row['historyable']['date'];
      $create[$key]  = $row['historyable']['created_at'];
   }

   array_multisort($date, SORT_DESC, $arr);
   array_multisort($create, SORT_DESC, $arr);

  return $arr;
 }

I don't know but it works for me.. but i still find the shorter way for this..