php - 具有自定义外键的 Laravel 多态

标签 php laravel polymorphism relationship

我对自定义 shipmentable_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 )

现在我的 Transfer 模型 realtion 是这样的:

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

问题是,到 shipmentable 表,到 shipmentable_type 列现在是这样的:App/Models/Transfer,但在这种情况下我想强制在那里“转移”。可能吗?

最佳答案

来自docs

By default, Laravel will use the fully qualified class name to store the type of the related model. However, you may wish to decouple your database from your application's internal structure. In that case, you may define a relationship "morph map" to instruct Eloquent to use a custom name for each model instead of the class name:

use Illuminate\Database\Eloquent\Relations\Relation;

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

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

关于php - 具有自定义外键的 Laravel 多态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48435989/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

mysql - 不要在数据库中创建字段

php - 如何在 Laravel 中动态重置数据库配置?

php - Laravel:有几个种子表属于使用工厂的关系

polymorphism - Hack语言会支持函数重载多态吗?

php - 我正在尝试使用 php 代码删除使用复选框选择的行

php - MySQL 查询在 mysql 中返回行,但在 PHP 中返回空集

php - Docker:如何安装 PHP 7.4 扩展 ext-http?

c# - 当成员字段是对象的集合并且也是继承树的一部分时,成员字段中的多态性

java - 根据构造函数参数实例化特定的子类型