如何手动设置存储在多态关系模型类型列中的值?

How to manually set the value that is stored in model type column in polymorphic relations?

考虑下表:

staff
    id - integer
    name - string

products
    id - integer
    price - integer

photos
    id - integer
    path - string
    imageable_id - integer
    imageable_type - string

Laravel 默认将模型名称 class 存储在 imageable_type 列中。例如 App\ProductApp\Staff。如何手动设置类型值?例如productstaff

我不确定您为什么要这样做,但是,查看 MorphMany() 方法的签名:https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Model.html#method_morphMany

MorphMany morphMany(string $related, string $name, string $type = null, string $id = null, string $localKey = null)

您可以更改 $type 字符串。

在 Laravel >= 5.1.14 上,您应该设置静态 Relation::morphMap 属性 来为您的应用程序定义所有变形 类。

在您的 AppServiceProviderboot() 方法中,添加以下内容:

\Illuminate\Database\Eloquent\Relations\Relation::morphMap([
    'product' => 'App\Product ',
    'staff' => 'App\Staff ',
]);

如果使用 Laravel < 5.1.14,则 morphMap 功能不存在。但是,您可以在模型上设置 morphClass 属性。这将允许您设置 *_type 字段中使用的值。

class Product extends Model
{
    protected $morphClass = 'product';
}

class Staff extends Model
{
    protected $morphClass = 'staff';
}

但是,这种方法的问题是您无法从变形记录中获取父记录。因此,如果您有产品或员工模型,您将能够很好地获得照片。但是,如果您有照片模型,您将无法轻松获得相关的产品或员工记录。描述了问题和问题的解决方案

Laravel >= 5.1.14 中提供的 morphMap 功能没有这个问题。