Laravel框架中的继承 [英] Inheritance in Laravel framework

查看:122
本文介绍了Laravel框架中的继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能在laravel模型中使用遗传?我解释说:



是否可以发布一个扩展雄辩类的模型?

  class A扩展Eloquent 
{
}

class B extends A
{
}

A e B也是2个不同的表,B有A_id作为外键和其他字段。
怎么可能是B类的构造函数?
是一个可怕的解决方案还是更好的使用hasOne关系?



不是每个A对象也是B对象。 ES。用户和老师



谢谢

解决方案

我有困难了解你的补充细节,但是在回答实际问题的时候:是的,有可能延伸卓越的型号。

  php 
class用户扩展\Eloquent {

protected $ table ='users';

}

class学生扩展用户{

protected $ table ='students';

}

尽管警告,任何方法(如关系,范围等)传播到扩展类。如果不希望这样做,那么创建一个基本类,其中最少需要你所需的,然后用你的具体类型进行子类化,即 Student 管理员等。



另一种方法是使用界面。所以如果你知道模型需要相同的属性,但会说,有不同的关系;那么你可以创建一个界面来添加这些约束:

   interface UserInterface {

public function getName();

}

类用户扩展\Eloquent实现UserInterface {

protected $ table ='users';

public function getName()
{
return $ this-> name;
}

}

class学生扩展\Eloquent implements UserInterface {

protected $ table ='students';

public function getName()
{
return $ this-> name;
}

public function courses()
{
return $ this-> belongsToMany('Course');
}

public function scores()
{
return $ this-> hasMany('Grade');
}

}


Is possibile to use inheritance in laravel model? I explain:

is possible to exend a model, which extends eloquent class?

class A extends Eloquent
{
}

class B extends A
{
}

A e B are also 2 different tables and B has A_id as foreignkey and other fields. How could be the constructor of class B? is it a ragionable solution or better use hasOne relationship?

no every A object are also B object. Es. user and teacher

Thank you

解决方案

I’m having difficulty understanding your supplementary details, but in answer to the actual question: yes, it is possible to extend Eloquent models.

<?php
class User extends \Eloquent {

    protected $table = 'users';

}

class Student extends User {

    protected $table = 'students';

}

Be warned though, that any methods (such as relations, scopes etc) will propagate to the extending class. If this is not desired, then create a base class that has the minimum of what you need, and then sub-class it with your specific types, i.e. Student, Administrator etc.

Another approach is to use interfaces. So if you know models need the same attributes but will say, have different relations; then you can create an interface to add those constraints:

<?php
interface UserInterface {

    public function getName();

}

class User extends \Eloquent implements UserInterface {

    protected $table = 'users';

    public function getName()
    {
        return $this->name;
    }

}

class Student extends \Eloquent implements UserInterface {

    protected $table = 'students';

    public function getName()
    {
        return $this->name;
    }

    public function courses()
    {
        return $this->belongsToMany('Course');
    }

    public function grades()
    {
        return $this->hasMany('Grade');
    }

}

这篇关于Laravel框架中的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆