Laravel中的模型继承

Gab*_*ich 20 model laravel eloquent

我目前正在与Laravel合作,我正在努力解决每个模型需要从Eloquent扩展的事实,我不确定如何实现模型层次结构(使用不同的表)

例如:

假设我有一个抽象模型Tool,然后是Hammer一个Screwdriver从Tool扩展的模型和模型.

现在,工具将扩展Eloquent ......但是,没有工具表,有一个Hammers表和另一个螺丝刀表,因为它们具有不同的属性.

如何指定Hammer有一个表,而Screwdriver在扩展 Tool 时有一个表?我如何使用Eloquent来调用,例如,所有工具?

喜欢:

Tools::all()
Run Code Online (Sandbox Code Playgroud)

这应该带来所有的锤子和螺丝刀,因为它们都是工具

使用Eloquent可以吗?

Joo*_*ost 10

尽管我喜欢多态关系(PR)方法略好于单表继承(STI),但它仍然感觉不像真正的继承方法.从域(例如UML类图)的角度来看,它就像尝试使用组合关系而不是继承.

从数据库一致性的观点来看,多态关系本身在Laravel(恕我直言)中已经是一个非常奇怪的解决方案.由于不能有单个字段作为多个表的外键,这可能导致加入不应加入的ID.和不遵守的反向关系.

虽然我实际上并没有描述问题的解决方案,但我提出的方法与PR和STI不同.这个解决方案类似于Hibernate的每子类表方法.我认为Dauce对Eloquent的扩展是朝着同一个方向发展的,除了似乎仍有一些实施问题.

从数据库的角度来看,每个子类的表也意味着超类每个直接子类包含一列.然后,您可以将外键约束放在(非null)id上,并正确使用这些关系.但是,在Laravel的魔法Eloquent类中仍然应该有一些额外的逻辑,它将请求的对象转换为正确的类型.

所以对我来说,功能上,Eloquent模型应该在PHP端正确继承,而数据库仍然可以使用外键约束.


The*_*pha 8

注意:您不能直接使用抽象类,它必须由子类扩展

如果你的Tool(abstract)模型没有任何table映射到它,那么你不需要使用Tool::all,你不能直接使用/实例化abstract模型,但你可以使用该abstract模型作为基类,如下所示:

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
}
Run Code Online (Sandbox Code Playgroud)

使用HammerScrewdriver直接,但从来没有在Tool模型/类,因为它是一个abstract类,例如:

$hammers = Hammer:all();
Run Code Online (Sandbox Code Playgroud)

或者类似这样的事情:

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