Laravel hasMany with where

后端 未结 2 1735
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 02:56

I have 3 tables, Cars, Flats and Shops. Each table has its photos. Photos is stored in database. I want to use only one table for photos, I don\'t want to create Photos table fo

2条回答
  •  甜味超标
    2021-02-01 03:29

    You can make use of Eloquent's Polymorphic relationships. The example in the Laravel Documentation actually showcases setting up a common images table for multiple models, so that should point you in the right direction. In your case something your models would look something like this:

    class Photo extends Eloquent {
    
        public function imageable()
        {
            return $this->morphTo();
        }
    
    }
    
    class Car extends Eloquent {
    
        public function photos()
        {
            return $this->morphMany('Photo', 'imageable');
        }
    
    }
    
    class Flat extends Eloquent {
    
        public function photos()
        {
            return $this->morphMany('Photo', 'imageable');
        }
    
    }
    
    class Shop extends Eloquent {
    
        public function photos()
        {
            return $this->morphMany('Photo', 'imageable');
        }
    
    }
    

    And you could access the photos for, let's say a given Flat, like this:

    Flat::find($id)->photos;
    

    For this to work you'd also need to add 2 additional columns to your photos table:

    imageable_id: integer  <-- This will be the ID of the model
    imageable_type: string <-- This will be the model's class name (Car/Flat/Shop)
    

提交回复
热议问题