【问题标题】:Is there a way to morph a Laravel Eloquent model?有没有办法改变 Laravel Eloquent 模型?
【发布时间】:2015-08-10 19:00:59
【问题描述】:

我有一个Detail(代表订单详细信息)模型,我想将其转换为销售订单详细信息或采购订单详细信息。因此,我创建了一个具有“类型”列的表,该列的值为“销售”或“购买”。

我的问题是,在 Laravel 中是否有一种方法可以将 Detail 模型变形为 Sale and Purchase,例如,如果我调用 App\Sale::all() 它会获取 App\Detail::all()->where('type','sale')

【问题讨论】:

  • Yes
  • @MartinBean 你能说得更具体点吗?
  • 你的 Detail 模型应该是可变形的,SalePurchase 模型应该变形为它。
  • @MartinBean 和下面zianwar的回答一样吗?

标签: php laravel eloquent


【解决方案1】:

设置数据库表:

你可以在这个结构中设置你的数据库表:

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

【讨论】:

  • 我不知道,但在我看来,多态关系不是为这种情况设计的。而且这种方式实际上需要在数据库中添加我不喜欢的其他表。
【解决方案2】:

虽然我还没有找到一种“官方”的方式来将一个类转变为另一个类。我开发了以下可能是解决方案的方法。

首先,定义两个模型SalePurchase扩展Detail,并使用稍后定义的特征。

类销售扩展细节{ 使用 SaleTrait; }

然后,使用GlobalScope 将约束添加到查询构建器。步骤如下:

  1. SalePurchase 模型定义一个特征,
特征 SaleTrait { 公共静态函数 bootSaleTrait() { 静态::addGlobalScope(new ActiveEventsScope); } }
  1. 然后定义范围。注意:这里我没有实现ScopeInterface,而是扩展了Sofa\GlobalScope,它为我处理remove()方法,所以我只需要在范围内定义apply()
SaleScope 类扩展了 GlobalScope { 公共函数应用(生成器 $builder,模型 $model) { $builder->where('type', 'sale'); } }
  1. 现在我可以使用App\Sale::all()App\Purchase::all() 只检索我想要的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-09
    • 2020-02-16
    • 1970-01-01
    • 2020-07-10
    • 2011-10-29
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多