Question

i understand how the polymorphic relations works, but still i don't understood how can i get the results of table morphed associating to the respective tables. Let's go with a example for understand better.

we have the normal example with History, Order, and User table.

History | table

id
historable_id
historable_type
event

Orders | table

id
order

Users | Table

id
fullname

Then let's go with the our polymorphic relationship:

History model

Class History extends Eloquent {
 function historable() {
   $this->morphTo();
 }

}

User model

Class User extends Eloquent {
   function history() {
     $this->morphMany('History','historable');
   }
}

Order model

Class Order extends ELoquent {
  function hisotry() {
    $this->morphMany('History','historable');
  }
}

Now if i want get all the users history i can just do something like that

$user = User::find(1);
foreach ($user->historable as $history) {
  echo "Name:".$user->fullname;
  echo "Event:".$history->event;
}

My question is, how can get both of the history of users and orders in one selection and automatically it associates with the datas belonging?

Example of my expectation of the result:

<h2>History</h2>
<table>
  <tr>
   <th>id</th>
   <th>Category</th>
   <th>Name</th>
   <th>Event</th>
  </tr>
  <tr>
   <td>1</td>
   <td>Order</td>
   <td>SmartPhone</td>
   <td>Bought</td>
  <tr>
  <tr>
   <td>2</td>
   <td>User</td>
   <td>Jhon Smith</td>
   <td>Book SmartPhone</td>
  </tr>
</table>
Was it helpful?

Solution

You can using History class as a normal eloquent model. The historable relation on the History model will return either a User or Order instance.

And for your expected result, code may be like:

$histories = History::all();

foreach ($histories as $history) {
  echo 'ID:' . $history->id;
  echo 'Category:' . ($history->historable instanceof User) ? 'User' : 'Order';
  echo 'Name:' .  ($history->historable instanceof User) ? $history->historable->fullname  : $history->historable->order ;
  echo "Event:".$history->event;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top