首页 > 解决方案 > 继承的多态关系

问题描述

在我的数据库中,我有一个继承的情况。
有一个名为Products的表,其中包含所有类别(如SuitsFootwearsFabric Packs )之间的共同属性,每个产品应该只是提到的类别之一。
我已经使用该方法$table->morphs('taggable');创建了适当的列。
并像这样实现了 eloquent 的多态关系:

    class Product extends Model
{
    public function taggable()
     {
         return $this->morphTo();
     }

}


class Footwear extends Model
{
    public function product()
    {
        return $this->morphMany('Product', 'taggable');
    }
}


其他两个班级也是如此。但是当我使用修补程序来验证关系时,它似乎从一侧起作用!

>>> App\Model\Product::find(65)->taggable
[!] Aliasing 'FabricPack' to 'App\Model\FabricPack' for this Tinker session.
=> App\Model\FabricPack {#2928
     id: 5,
     length: 0.7,
     created_at: "2018-07-30 12:19:51",
     updated_at: "2018-07-30 12:19:51",
   }


我认为App\Model\FabricPack::find(5)->tag应该返回适​​当的产品,而是返回 null。

>>> App\Model\FabricPack::find(5)
=> App\Model\FabricPack {#2929
     id: 5,
     length: 0.7,
     created_at: "2018-07-30 12:19:51",
     updated_at: "2018-07-30 12:19:51",
   }
>>> App\Model\FabricPack::find(5)->tag
=> null


那么,这个问题的任何解决方案?

标签: laravel-5.6relationships

解决方案


taggable_type值应该是这样App\Model\{subclass}的。


推荐阅读