【问题标题】:Laravel-4 Polymorphic Relationship showing both type with the respective tablesLaravel-4 多态关系显示两种类型与各自的表
【发布时间】:2014-01-10 05:46:01
【问题描述】:

我了解多态关系是如何工作的,但我仍然不明白如何获得与各个表关联的表变形的结果。让我们举个例子更好地理解。

我们有 History、Order 和 User 表的常规示例。

历史 |表格

id
historable_id
historable_type
event

订单 |表格

id
order

用户 |表格

id
fullname

那么让我们来看看我们的多态关系:

历史模型

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

}

用户模型

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

订单模式

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

现在,如果我想获取所有用户历史记录,我可以这样做

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

我的问题是,如何在一次选择中同时获取用户和订单的历史记录并自动关联到所属的数据?

我对结果的期望示例:

<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>

【问题讨论】:

    标签: php orm laravel-4 eloquent polymorphic-associations


    【解决方案1】:

    您可以使用History 类作为普通的 eloquent 模型。 History 模型上的 historable 关系将返回 UserOrder 实例。

    对于您的预期结果,代码可能如下:

    $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;
    }
    

    【讨论】:

      猜你喜欢
      • 2020-10-17
      • 2018-09-17
      • 2019-11-05
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 2014-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多