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

问题描述 投票:1回答:2

请考虑以下表格:

staff
    id - integer
    name - string

products
    id - integer
    price - integer

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

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

laravel polymorphic-associations
2个回答
3
投票

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

boot()AppServiceProvider方法中,添加以下内容:

\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';
}

但是,这种方法的问题是,您将无法从变形记录中获取父记录。因此,如果您具有产品或职员模型,则可以很好地获取照片。但是,如果您有照片模型,将无法轻松获得相关的产品或员工记录。 this question and answer描述了该问题及其解决方案。

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


0
投票

我不确定为什么要这样做,但是请查看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字符串。

© www.soinside.com 2019 - 2024. All rights reserved.