我有一个Detail
(表示订单详细信息)模型,我想将其转换为销售订单详细信息或采购订单详细信息。因此,我创建了一个具有"type"列的表,其值为"sale"或"purchase"。
我的问题是,是否有一种方法在Laravel,我可以改变细节模型的销售和购买,所以,例如,如果我调用App'Sale::all()
它会获取App'Detail::all()->where('type','sale')
?
设置数据库表:
你可以这样设置你的数据库表:
purchases
id - integer
price - string
sales
id - integer
price - integer
details
id - integer
description - string
detailable_id - integer
detailable_type - string
设置模型:
<?php
namespace App;
use Illuminate'Database'Eloquent'Model;
class Detail extends Model
{
// Get all of the owning detailable models.
public function detailable()
{
return $this->morphTo();
}
}
class Sale extends Model
{
// Get all of the sales member's order details.
public function details()
{
return $this->morphMany('App'Detail', 'detailable');
}
}
class Purchase extends Model
{
// Get all of the purchase's order details.
public function details()
{
return $this->morphMany('App'Detail', 'detailable');
}
}
检索数据:
然后你可以像这样检索你的销售额:
$sales = App'Sale::find(1);
foreach ($sales->details as $order_detail) {
//
}
购买也是如此:
$purchases = App'Purchase::find(1);
foreach ($purchases->details as $order_detail) {
//
}
更多关于多态关系的信息:http://laravel.com/docs/5.1/eloquent-relationships#polymorphic-relations
虽然我还没有找到一种"官方"的方式来将一个类转换为另一个类。我想出了一个可能的解决办法:
首先,定义扩展Detail
的两个模型Sale
和Purchase
,并使用稍后将定义的特性。
然后,使用GlobalScope向查询生成器添加约束。步骤如下:
- 为
Sale
和Purchase
模型定义一个trait,
- 然后定义作用域。注意:这里不是实现ScopeInterface,我扩展了Sofa'GlobalScope,它为我处理
remove()
方法,所以我只需要在作用域中定义apply()
。<>之前类SaleScope扩展了GlobalScope{应用(Builder $ Builder, Model $ Model){构建器->,("类型","销售");}}之前- 现在我可以使用
App'Sale::all()
和App'Purchase::all()
只检索我想要的。
- 现在我可以使用