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