Laravel: Returning the namespaced owner of a polymorphic relation

后端 未结 6 2006
刺人心
刺人心 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 10:57

    In order for eager loading of polymorphic relations eg Photo::with('imageable')->get(); it's necessary to return null if type is empty.

    class Photo extends Eloquent {
    
        protected $types = [
            'order' => 'App\Store\Order',
            'staff' => 'App\Users\Staff'
        ];
    
        public function imageable()
        {
            return $this->morphTo();
        }
    
        public function getImageableTypeAttribute($type) {
            // Illuminate/Database/Eloquent/Model::morphTo checks for null in order
            // to handle eager-loading relationships
            if(!$type) {
                return null;
            }
    
            // 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'
        }
    
    }
    

提交回复
热议问题