Model Inheritance in Laravel

前端 未结 4 783
别那么骄傲
别那么骄傲 2020-12-23 21:51

i\'m currently working with Laravel and I\'m struggling with the fact that every model needs to extend from Eloquent and I\'m not sure how to implement a model Hierarchy

4条回答
  •  没有蜡笔的小新
    2020-12-23 22:44

    Note: You can't use an abstract class directly, it has to be extended by a child class

    If your Tool (abstract) model doesn't have any table mapped to it then you don't need to use Tool::all and you can't directly use/instantiate an abstract model but you may use an that abstract model as a base class like this:

    abstract class Tool extends Eloquent {
    
        protected $validator = null;
        protected $errors = null;
        protected $rules = array();
    
        // Declare common methods here that
        // will be used by both child models, for example:
    
        public static function boot()
        {
            parent::boot();
            static::saving(function($model)
            {
                if(!$this->isvalid($model->toArray(), $this->rules) return false;
            });
        }
    
        protected function isvalid($inputs, $rules)
        {
            // return true/false
            $this->validator = Validator::make($inputs, $rules);
            if($this->validator->passes()) return true;
            else {
                $this->errors = $this->validator->errors();
                return false;
            }
        }
    
        public function getErrors()
        {
            return $this->errors;
        }
    
        public function hasErrors()
        {
            return count($this->errors);
        }
    
        // declare any abstract method (method header only)
        // that every child model needs to implement individually
    }
    
    class Hammer extends Tool {
        protected $table = 'hammers';
        protected $fillable = array(...);
        protected $rules = array(...); // Declare own rules
    
    }
    
    class Screwdriver extends Tool {
        protected $table = 'screwdrivers';
        protected $fillable = array(...);
        protected $rules = array(...); // Declare own rules
    }
    

    Use Hammer and Screwdriver directly but never the Tool model/class because it's an abstract class, for example:

    $hammers = Hammer:all();
    

    Or maybe something like this:

    $screwdriver = Screwdriver:create(Input::all());
    if($screwdrivers->hasErrors()) {
        return Redirect::back()->withInput()->withErrors($screwdriver->getErrors());
    }
    return Redirect::route('Screwdriver.index');
    

提交回复
热议问题