Laravel 4, Multiple Polymorphic Relations from one Model

后端 未结 1 647
再見小時候
再見小時候 2021-02-03 11:51

I\'m trying to set up polymorphic relationships in Laravel 4 so that I can have one Image class which handles everything related to uploads, unlinks and so on, then have it used

相关标签:
1条回答
  • 2021-02-03 12:05

    No built-in way right now. Maybe in Laravel 4.1 that's supposed to bring a complete rewrite of polymorphic relations.

    Add a type property to Image, then define where conditions on the relations:

    public function mugshot() { 
        return $this->morphOne('Image', 'of')->where('type', 'mugshot'); 
    }
    
    public function photos() { 
        return $this->morphMany('Image', 'of')->where('type', 'photo'); 
    }
    

    Don't forget to set type on Images you create. Or, like I did bellow, hide that logic inside the model.

    Here's my code (I'm using PHP 5.4 with short array notation):

    Image:

    namespace SP\Models;
    
    class Image extends BaseModel {
    
        const MUGSHOT = 'mugshot';
        const PHOTO = 'photo';
    
        protected $hidden = ['type'];
    
        public function of()
        {
            return $this->morphTo();
        }
    }
    

    Person:

    namespace SP\Models;
    
    use SP\Models\Image;
    
    class Person extends BaseModel {
    
        public function mugshot() { 
            return $this->morphOne('SP\Models\Image', 'of')
                                ->where('type', Image::MUGSHOT); 
        }
    
        public function photos() { 
            return $this->morphMany('SP\Models\Image', 'of')
                                ->where('type', Image::PHOTO); 
        }
    
        public function saveMugshot($image)
        {
            $image->type = Image::MUGSHOT;
            $image->save();
            $this->mugshot()->save($image);
        }
    
        public function savePhotos($images)
        {
            if(!is_array($images))
            {
                $images = [$images];
            }
    
            foreach($images as $image)
            {
                $image->type = Image::PHOTO;
                $image->save();
                $this->photos()->save($image);
            }
        }
    }
    

    Somewhere in a controller/service:

    $person->savePhotos([$image1, $image2]);
    
    0 讨论(0)
提交回复
热议问题