Laravel: Returning the namespaced owner of a polymorphic relation

后端 未结 6 2020
刺人心
刺人心 2020-12-02 10:28

I can find a number of discussions regarding this but no clear solution. Here are two links, although I will cover everything in my own question here.

Github Issues<

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 11:03

    I like @JarekTkaczyks solution and I would suggest you use that one. But, for the sake of completeness, there's is another way Taylor briefly mentions on github

    You can add a attribute accessor for the imageable_type attribute and then use a "classmap" array to look up the right class.

    class Photo extends Eloquent {
    
        protected $types = [
            'order' => 'App\Store\Order',
            'staff' => 'App\Users\Staff'
        ];
    
        public function imageable()
        {
            return $this->morphTo();
        }
    
        public function getImageableTypeAttribute($type) {
            // transform to lower case
            $type = strtolower($type);
    
            // to make sure this returns value from the array
            return array_get($this->types, $type, $type);
    
            // which is always safe, because new 'class'
            // will work just the same as new 'Class'
        }
    
    }
    

    Note that you still will need the morphClass attribute for querying from the other side of the relation though.

提交回复
热议问题