[英]Is there a way to morph a Laravel Eloquent model?
我有一个Detail
(代表订单明细)模型,我想将其变形为销售订单明细或采购订单明细。 因此,我创建了一个具有“类型”列的表,该列的值将为“销售”或“购买”。
我的问题是,在Laravel中,有没有一种方法可以将Detail模型变形为Sale和Purchase,例如,如果我调用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
模型,并使用稍后定义的特征。
class Sale extends Detail { use SaleTrait; }
然后,使用GlobalScope向查询构建器添加约束。 步骤如下:
Sale
和Purchase
模型, trait SaleTrait { public static function bootSaleTrait() { static::addGlobalScope(new ActiveEventsScope); } }
remove()
方法,因此我只需要在范围中定义apply()
。 class SaleScope extends GlobalScope { public function apply(Builder $builder, Model $model) { $builder->where('type', 'sale'); } }
App\\Sale::all()
和App\\Purchase::all()
来仅检索我想要的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.