Search code examples
laravel-5.6relationships

Polymorphic Relations for inheritance


in my database, I have an inheritance situation.
there is a table called Products that holds the common attributes among all the categories like Suits, Footwears and Fabric Packs, each product should be only one of the mentioned categories.
i've used the method $table->morphs('taggable'); to create the appropriate columns.
and implemented polymorphic relationships of eloquent like this:

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

}


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


th same thing in the other two classes. but when i use tinker to verify the relationship it seems to work from one side !

>>> 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",
   }


i think App\Model\FabricPack::find(5)->tag should return the appropriate product but instead returns 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


so, any solution for this problem?


Solution

  • taggable_type values should like this App\Model\{subclass}.