【问题标题】:How to manually set the value that is stored in model type column in polymorphic relations?如何手动设置多态关系中模型类型列中存储的值?
【发布时间】:2016-01-23 11:51:38
【问题描述】:

考虑下表:

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


    【解决方案1】:

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

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

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

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

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

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

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

    【讨论】:

    • 4 年后,现在有了更好的解决方案:在 AppServiceProvider Relation::morphMap([ 'product' => 'App\Product ]);
    • @soundwave1337 morphMap 已经存在了一段时间。它通过 PR #9891 引入 5.1.14。
    【解决方案2】:

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

    【讨论】:

    • 他不想更改字段名,而是更改其中存储的值。
    猜你喜欢
    • 1970-01-01
    • 2021-05-23
    • 2014-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    相关资源
    最近更新 更多