【发布时间】: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