【问题标题】:Laravel polymorphic with custom foreign key具有自定义外键的 Laravel 多态
【发布时间】:2018-07-04 07:05:52
【问题描述】:

我对自定义 shipping_type 有疑问。我的结构是这样的:

transfers:
id - integer
name - string

shipment:
id - integer
name - string

shipmentale:
shipment_id - integer
shipmentable_id - integer
shipmentabl_type - enum ( transfer, order, complaint, internet )

现在我的传输模型中是这样的:

 public function shipments()
{
    return $this->morphToMany(Shipment::class, 'shipmentable');
}

问题是,table shippingable_type 现在是这样的:App/Models/Transfer,但在这种情况下我想强制“转移”。可能吗?

【问题讨论】:

标签: php laravel polymorphism relationship


【解决方案1】:

要在shipmentable_type 中设置模型的完全限定名称以外的值,可以使用Relation::morphMap() 函数。

Relation::morphMap([
    'transfer' => 'App/Models/Transfer'
]);

这应该在AppServiceProvider 或类似中设置。

【讨论】:

    【解决方案2】:

    来自docs

    默认情况下,Laravel 将使用完全限定的类名来存储相关模型的类型。但是,您可能希望将数据库与应用程序的内部结构分离。在这种情况下,您可以定义一个关系“变形图”来指示 Eloquent 为每个模型使用自定义名称而不是类名称:

    use Illuminate\Database\Eloquent\Relations\Relation;
    
    Relation::morphMap([
       'transfer' => 'App/Models/Transfer'
    ]);
    

    您可以在AppServiceProviderboot 功能中注册morphMap,或者如果您愿意,可以创建一个单独的服务提供商。

    【讨论】:

      【解决方案3】:

      我遇到过这个问题,但不幸的是,我有多个模型指向 transfer,并且有多个位置。您可以在模型上动态解决它们:

      class Transfers extends Model
      {
          /**
           * Declare the class to get connect polymorphic relationships.
           *
           * @var string|null
           */
          protected $morphClass = null;
      
          /**
           * Get the associated morph class.
           *
           * @return string|null
           */
          public function getMorphClass()
          {
              return $this->morphClass ?: static::class;
          }
      
          public function shipments()
          {
              $this->morphClass = 'transfer';
              return $this->morphToMany(Shipment::class, 'shipmentable');
          }
      
          // ...
      }
      

      【讨论】:

        猜你喜欢
        • 2021-04-04
        • 1970-01-01
        • 1970-01-01
        • 2021-07-27
        • 2021-12-12
        • 1970-01-01
        • 2021-12-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多